Install Google Chrome to Phone on Android TV – Casting PC browser URL to TV with one click

* The tips written here is not officially supported, and I don’t take any responsibility caused by using this Technique. Try it with your own responsibility.

Watch browser contents on TV more easily

When you are browsing on the Internet with PC or Smartphone/Tablet in home, especially when streaming video contents, have you ever wanted to see it on big TV display?

Android TV initially don’t support browser app (It is officially stated that Android TV may not have browser app initially), but you can install browser app on Android TV. For example, there is Web Browser for Android TV on Play Store now. Also, SONY Android TV contains Pre-installed OPERA browser for now. 

So you can watch any web contents on TV!! But the problem is,,, even if you have a specific website which you want to watch on TV in mind, navigating to this website on TV is quite troublesome since we usually don’t use keyboard to search contents within TV app (Android TV supports mouse and keyboard, so you can actually connect these devices to use TV like a PC, but TV is used with relaxing mode so few people uses such a way).

So I was thinking when I’m browsing on PC, it is nice if we could cast current URL on PC to Android TV so that we don’t need to type anything on TV side. And yes! we can utilize Android platform to achieve this request:)

 * Google cast also achieves this request, but sometimes it doesn’t work in my environment. So I will post different solution here.

Google Chrome to Phone app & Chrome to Phone extension

Google Chrome to Phone is made by Google, achieves to share links between your PC’s chrome and “device”. Of course the “device” is supposed to be a Android phone, but we can install Android phone’s app on Android TV as well by using the technique mentioned at 

Ok, so what we will install is following,

After installed app and plug-in, you need to set up both of them by logging in with same Google account.

How to use

After set up done, it is very easy to use and it is conveniently automated. We can cast PC side’s website URL to TV side and TV side automatically launch browser app to show this URL.

  1. PC side: Launch Chrome and go to your favorite website that you want to show on TV
  2. PC side: Click top-right icon
    Basically that’s all! Then,
  3. (This procedure might be necessary) Android TV side: launch browser app
  4.  Android TV side: browser app automatically move to the URL specified by PC side. 
    Enjoy watching web contents on big, beautiful TV display 🙂

Conclusion

Now the PC side web page can be sent to TV side by just one click, it enhanced my opportunity to enjoy many kinds of web video contents on TV. I realized some of the HD stream videos are quite nice to watch with TV.

If the PC and TV is in the same room, you can even utilize TV as second (or third) monitor to stream video/music even it is not connected via HDMI cable.

Let me know your idea of life hacking technique of Android TV as well!!

Blog renewal: Suitable design style layout for technical blog?

* This post is written in 2015 Oct, the design might change in the future.

Customizing WordPress theme “Graphy”
– Optimize blog design for technical blog –

It has been 4 month since I started this blog on June. I was just focusing on showing the main contents for the starting point. But now published posts was increased so that it is possible to show users “Related post” or “Popular post”.

This blog is powered by WordPress, by using free theme “Graphy“. It is really simple and beautiful design, makes us feel “reading” typography. I feel it is especially suitable for writing “novel” type posts so that user can concentrate on reading text. However, I prefer to change some styles to optimize it for my blog category “technology posting”. Here is a memo for these changing points and their reasons (Of course, these are just my personal opinion & preference).

Child theme

What is the best way to code your modification of original theme? If original theme codes are modified, these modification will disappear when we update this theme. To cope with these problems, WordPress supports a nice functionality called Child themes, so that user can implement their own customize in a separated module.

It works very similar to extending parent class in object oriented programming. So that you only need to overwrite the difference from parent theme. Let’s get a example by making graphy’s child theme!

At least you need to make 1 folder and 2 files.

1. Make directory named “graphy-child” at /wp-content/themes/ where all themes are stored. We can implement customized styles and codes in this folder.

2. Make style.css file inside graphy-child, must include following meta information.

/*
 Theme Name:   Graphy Child
 Theme URI:    https://wordpress.org/themes/graphy/
 Description:  Graphy Child Theme
 Author:       corochann
 Author URI:   http://corochann.com
 Template:     graphy
 Version:      1.0.0
 License:      GNU General Public License v2.0
 License URI:  http://www.gnu.org/licenses/gpl-2.0.html
 Tags:         white, light, white, one-column, two-columns, right-sidebar, responsive-layout, custom-background, custom-colors, custom-header, custom-menu, editor-style, featured-images, microformats, post-formats, sticky-post, theme-options, threaded-comments, translation-ready
 Text Domain:  graphy-child
*/
  • Template attribute is important, we need to specify parent themes folder name.
  • Theme Name will appear on your Admin panel’s “Manage Themes” page. 

3. Make functions.php file inside graphy-child, write following

<?php
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}

Note that child theme’s functions.php does not overwrite parent’s functions.php, instead, it is loaded right before the parent’s functions.php. So we don’t need to copy paste parent’s file, but just need to implement our own additional functions.

Ok, minimum implementation is done. We can now choose “graphy-child” theme from Dashboard → Appearance → Themes.

Child theme will appear on the WordPress dashboard

Now we can proceed to customize the theme just by modifying child theme, especially style.css.

A. Single column? Two column? Three column?

To start considering a layout of the web site, the base layout should be determined. WordPress theme can be categorized either of below.

  • Single column
    It does show main contents in the center, while it is not good at showing other sub-contents/links.
    Suitable for those who want user to concentrate on reading main contents.
  • Two column
    It can show main contents in primary row as well as sub-contents in secondary row.
    Suitable if you want to include internal-links while maintaining simple design.
  • Three column
    There are two side bars among center main row. So you can put many sub-contents (profile, archives, related posts, popular posts, recent posts, advertisements, social icon, interlinkage etc…).
    Suitable for contents portal page, so that you want to show many attractive posts.

The support for these layout depends on the theme. Graphy supports single column and two column layout. Graphy is more focusing on simple design, showing main contents. 

I was using single column until today to focus on showing the main contents. But I want to navigate user to other contents as well now, so I have changed layout to two column to show “Related post” and “Popular post”.

WordPress Popular Posts plug in – Showing popular post

“Related post” can be displayed from default customization, but “popular post” is not possible since WordPress don’t save the number of views by default. However, we can show popular posts very easily by installing plug in. Famous plug in is WordPress Popular Posts and WP-PostViews. I adopted WordPress Popular Posts, you can seepopular posts ranking as well as number of views at the right-top corner.

B. Layout width change

Source code is frequently written in this blog, and it is nice to show one line programming in one line. Therefore, I wanted to keep main contents area wide enough. To prevent the side effect of layout change to two column, I increased the width attribute of main layout.

C. Make texts more packed – change line height

I noticed there is a big spacing beween each line with Graphy’s original design. It emphasizes background white space, this is indeed one factor that contributes to make Graphy beautiful. It is good for reading novels, though it is not suitable for technical contents. When we study something, it is usually difiicult to understand the contents just by reading once. We often need to go back and forth while reading. Therefore, I prefer text contents to be packed so that we can refer previous sentence without scrolling so much. Textbooks, technical books, technical papers are mostly packed, aren’t they?

To make text more packed I did

  1. make text size small.
  2. decrease margin.
  3. decrease line spacing.
Implementation: Change CSS style font-size & line-height

Modify style.css. You can find at the wordpress Dashboard → Appearance → Editor → Styles (bottom-right) > Stylesheet > style.css

font-size attribute defines the spacing/margin between lines, change it for your preference. I decreased the header’s font size in this blog.

margin-bottom, margin-top attributes are used to dtermine the spacing/margin between each blocks. I decreased the “Asap”, “Verdana”, “Arial”, and “sans-serif” font for this blog.

line-height attribute defines the spacing/margin between lines, change it for your preference. I decreased the values from original.

D. Change style of code attribute

code and pre attributes are important to explain about methods, class, or source code etc. I put color on code HTML tag attribute.

Reference

15 Best Free Android TV game app which played with gamepad

It is nice to know that A button is used for proceed, and B button is used for back.

* The number of installs are based on the time of writing, 2015/10/11.

Beach Buggy Racing

  • Installs: 10M ~
  • Offered by: Vector Unit

It is a racing game similar to Mario Kart. You can use item to power-up or defeat other cars during the race. Graphics is animation style rather than realistic, so it is well acceptable for whole family (especially child).

Download on Google Play Store

Real Boxing

  • Installs: 10M ~
  • Company: Vivid Games S.A.

It is an action game. The graphics is very smooth 3D. You can use left joy stick for move and right joy stick for punch. You need to remember a little bit of command to play, so it is not simple compared to other games, but there is a Tutorial at the first time of game play and you can understand how to enjoy game. 

Download on Google Play Store

Turbo Driving Racing 3D

  • Installs: 10M ~
  • Offered by: TerranDroid

It is categorized in an runner game, rather than racing game. It is gameover when you crash other cars with the speed more than 60km/h. 

Download on Google Play Store

DEAD TRIGGER 2

  • Installs: 10M ~
  • Offered by: MADFINGER Games

It is FPS (First Person Shooting) game. The game is subjective view, so you can feel realistic, dynamic world in the game. It feels like it targets simply enjoyable game with story rather than complicated action game. For example, the attack is done by automatically when you set your sights on enemy. It is amazing that we can enjoy these games for free without console games nowadays!

Download on Google Play Store

Defender II

  • Installs: 10M ~
  • Offered by: DroidHen

It is a tower defense game, goal to protect your city on the left side from monsters coming from right side. You can use bow and magic to defeat monsters. When I play game was easy and rule was simple, easy to enjoy.

Download on Google Play Store

Daytona Rush

  • Installs: 5M ~
  • Offered by: Invictus Games Ltd.

It is a runner game, similar to “Despicable Me” and “Turbo Driving Racing 3D”. But it is racing field, I felt more speedy.

Download on Google Play Store

The Walking Dead series

The Walking Dead : Season One

  • Installs: 5M ~
  • Offered by: Telltale Games
You need to make choice through the game, which affects the story.
The game is more like playing story.

Download on Google Play Store

The Walking Dead : Season Two

  • Installs: 5M ~
  • Offered by: Telltale Games
You often need to make decision of your action.

It’s an adventure game, more concretely it is like “playing movie”. It is focusing on story rather than action. You have so huge number of times of chance to choice your action, even for the reply of daily conversation. You can also enjoy a little bit of an action when fighting with living dead. The game contains violence and scary, suitable for adults. As you can see, the graphics is realistic, which is a nice point but at the same time one dis advantage is that the size of the game is big (season one: 1.3 GB, season two 700 MB).

For the season two, you can take over the save data of Season one. the choice made in season one affects the story of season one. You might need to pay for enjoying next episode.

Download on Google Play Store

The Wolf Among Us

  • Installs: 1M ~
  • Offered by: Telltale Games

An adventure game, same system with “the walking dead series” above (Of course, same company is creating it).

Download on Google Play Store

Magic Rampage

  • Installs: 1M ~
  • Company: Asantee

It is platform action game, but you can have various weapons, armors to make hero strong. Each stage is called “Chapter X, dangeon Y” and the game is storynized.

Download on Google Play Store

Overkill 3

  • Installs: 1M ~
  • Offered by: Craneballs

FPS (First Person Shooting) game. It contains typical elements for these shooting games like aiming target, shooting, reloading, hide to wall, change gun, precise aiming mode… You can get strong weapons when you pay money.

Download on Google Play Store

Drift Mania: Street Outlaws LE

  • Installs: 1M ~
  • Offered by: Ratrod Studio Inc.

It is a racing game, the difference comes from it is focusing on drift experience. If you practice and become good player, you can enjoy drifting the courses all over the world! 

Download on Google Play Store

Radiant Difense

  • Installs: 1M ~
  • Company: HEXAGE

Strategy Tower Defense game. Place the weapons to block aliens invasion.

Download on Google Play Store

Epic Heroes War

  • Installs: 500K ~
  • Company: DIVMOB CO., LTD

Action fighting game. Heroes’ need to level-up and weapon  becomes stronger to go further stage.  The game is also compatible with remote controller.

Download on Google Play Store

Sword Of Xolan

  • Installs: 100K ~
  • Company: Yodo1 games

It is a simple platform action game, similar to super mario. Hero goes the stage and help caught people. The game is designed with old style “dot” picture, which makes the world cuter.

Download on Google Play Store

10 Best Free Android TV game app which you can enjoy without gamepad

Not long time past since “Android TV” is released, but some interesting games are already released for this Android TV market. You can enjoy all following game for free. But of course, the app developer is making these game apps for business, there’s a in-app purchase for almost all the games. Usually, you need to pay when you want to resume at gameover timing or you want to get extra power up items in the game.

* The number of installs are based on the time of writing, 2015/10/11.

Despicable Me: Minion Rush

Simple runner action game like Crossy Road, though the difference comes to the graphics which is well-made 3D.

Download on Google Play Store

Crossy Road

  • Installs: 50M ~
  • Offered by: Yodo1 games

It is very simple, “endless arcade hopper” game. Yes, it is endless. You can try and continue as far as you can go. There are many characters, e.g. pack man, chicken, etc. After you get coin in the game or purchasing, you can play the game with these characters.

Download on Google Play Store

Asphalt: Airborne 8

The exciting race game! As you can see, the graphics is so nice and music is also very dynamic and exciting when you play with the TV! I feel it is really good to play with big TV display, rather than just a hand phone.

There are many racing games on Android TV Google Play Store, but many of them requires game pad to play. The game made by Gameloft is very well-made in detail. It can be played without game pads or you can play with remote controllers as well. When I play with SONY BRAVIA, it detected remote controller, and shows the Tutorial specific for this remote controller.

Download on Google Play Store

Red Ball 4

  • Installs: 10M ~
  • Developer: FDG Entertainment GmbH & Co.KG

It is also an simple platform action game. The biggest difference from other game is that hero is ball, which has an inertia to keep rotating.

Download on Google Play Store

BADLAND

  • Installs: 10M ~
  • Offered by: Frogmind

Simple runner action game as well. But it is more simple that only “center” key is enough for playing game. Nice thing is you can enjoy a game. Even you die in the game, you can continue without pay extra money.

Download on Google Play Store

Spider Solitaire

  • Installs: 5M ~
  • Offered by: 1bsyl

The card puzzle game, as you can easily imagine from image. At first I was thinking of a game Solitaire, but it was different. However, the rule is similar so you can play without any explanation if you know the rule of Solitare (and FreeCell). This game is not so difficult, I took around 30 min to win one game. See Wikipedia page for the details.

Download on Google Play Store

Jelly King: Rule The World

  • Installs: 5M ~
  • Offered by: Jellyking Studio

Very simple, easy platform action game. Hold left & right button to collect the ball.

Download on Google Play Store

Does not Commute

  • Installs: 1M ~
  • Offered by: Mediocre

This is a driving game, but not racing game. It was introduced as “A strategic driving game” in the Google Play Store. So why “strategic”? This game is unique that you will drive tens of cars  in the same map, and at the time when you drive new cars, old cars which you have driven interferes the way. You struggle because of your driving… The map made like 1970’s town together with the matching background jazz music makes this game atmosphere cool!

You can play the game only left and right key, thus without game pad. But you feel comfortable with gamepad, since X key can be used to rewind current stage.

Download on Google Play Store

PAC-MAN 256 – Endless Maze

  • Installs: 1M ~
  • Offered by: BANDAI NAMCO Entertainment Europe

I think no need to explain what PAC-MAN is. This is derivative version of PAC-MAN, that aims to go up upper and upper of this endless stage, which is similar to Crossy Road.

The game is free without power up, and you can pay as an option to get extra power up.

Download on Google Play Store

Sky Force Anniversary

  • Installs: 10K ~
  • Offered by: Infinite Dreams

Shooting game. The number of install looks small, this is just because the game is provided only for Android TV devices, while all other game apps above are provided both Android phone and TV devices.

You can also enjoy multi-player play. For example 1P uses remote controller & 2P uses game pad.

Download on Google Play Store

Comment

Game is now cross-platform

I could notice current game market trend during summarizing this post. Now game is made for cross-platform. Most of the popular game app is not only for Android TV, but it is for PC, Play Station 3 or 4, Wii, Android phone/tablet etc.  So, big game software companies are just importing existing game into Android TV platform. Since it was already made for other platform (using a big development cost), the quality of these cross-platform game is usually quite nice.

Importance of beautiful graphics and background music/sound

After experiencing to play Android TV games, I felt Android TV game and Android phone game are different. We can enjoy dynamic, beautiful graphics with big screen. Just a difference of screen size? I would say the difference of screen size provides different user experience!!!

Also, the importance of sound becomes much higher.  You might play Android phone games with mute, however, you definitely play Android TV games with (maybe big) sound. Especially for racing games or shooting games, the dynamic sound makes user’s emotion more exciting. Additionally, home theater system provides you much presence for the game.

Simple game is also just fine

As written above, most popular apps are high quality. Graphics is smooth 3D, and sound is also created deeply to express game world’s atmosphere.

This is an opposite comment from above, but there also is a demand to play simple, easy game for just enjoy a slice of time. It is possible to reach more than 1 Million download with simple game apps (like Jelly king, PAC-MAN), 1 Million is quite enough number isn’t it?

What kind of game is not yet on the Android TV market?

There already is action, racing, shooting, simple platform game on Google Play Store, even though the future market growth of Android TV market is not known yet.

As one opinion, I felt Music game is interesting. I found the app “Radiohammer Station” on Google Play Store, but it was not optimized for Android TV device yet. I could not play with game pad key.

Another category is Social game like FarmVille. Especially, it is a interesting topic to consider game for women. For example, housewife is alone in the house on the daytime of weekday, they are important target for TV market to consider.

Importing Android SDK with hidden APIs

How to import ActivityManagerNative?

My first motivation was to use AndroidManagerNative class, even you can find this class in Android open source project, you can’t use it in our app when you build with usual Android SDK.

Yes, some of the classes are hidden in SDK. More specifically, $SDK_PATH/platforms/android-xx/android.jar contains limited APIs for Android app developers.

I put memo how to use these hidden classes/methods in your Android app development from Android studio (which works with build.gradle).

Building Android SDK including all APIs

First step is to prepare library which includes hidden Android APIs. Below link answers how to do this.

How do I build the Android SDK with hidden and internal APIs available?

  1. Build the repo or download jars from https://sites.google.com/site/hippunosource/home/android/androidnohide-apiwo-shi-yongsuru-rifurekushonha-wei-shi-yong
  2. copy out out/target/common/obj/JAVA_LIBRARIES/framework_intermediates/classes.jar (better to rename it as something like framework_all.jar)
  3. config your project build path–>libraries –> add this external jars. In Order and Export, move it up and before android.jar

So after fullbuilding AOSP source code, you can get desired jar file at out/target/common/obj/JAVA_LIBRARIES/framework_intermediates/classes.jar
I will note it as framework_all.jar in the following.

Another way to build only SDK is to use below command. (Reference: How to build my own Android SDK)

make -j8 PRODUCT-sdk-sdk showcommands dist

See also Eclipse上からAndroidのHide APIを使用する(リフレクションは未使用) (maybe only for Eclipse user).

Adding library in Android studio

Copy this framework_all.jar file at app/libs folder in your Android project, right click and choose “Add as library”

Now you can import hidden API, e.g. ActivityManagerNative!

However building failed. Because framework_all.jar is big library, including many methods, which causes some error while building.

build.gradle settings: compile error fix for including framework_all.jar 

java.lang.OutOfMemoryError: GC overhead limit exceeded

Add following options to increase java heap size,

android {
    ...
    dexOptions {
        javaMaxHeapSize "4g"
    }
}

Reference: Android Studio Google jar causing GC overhead limit exceeded error

trouble writing output: Too many method references: 83845; max is 65536.

There is a limitation dx compiler, up to 65536 method references is allowed per one dex file, while framework_all includes more than 65536 methods. I got following error

trouble writing output: Too many method references: 83845; max is 65536.
You may try using --multi-dex option.
References by package:
 27 android
 147 android.accessibilityservice
 598 android.accounts
 ...

To cooperate this, add multiDexEnabled options to support multidex inside defaultConfig closure,

android {
    ...
    defaultConfig {
        applicationId "..."
        minSdkVersion 22
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"

        // Enabling multidex support.
        multiDexEnabled true
    }
}

Reference

Noticeable changes for Android Marshmallow 6.0

What has changed from Android Lollipop to Marshmallow from user point of view on Android TV? Below is the noticeable changes when I use Nexus Player with Android Marshmallow (see how to update).

Precise permission control for each App

When we go to [Settings] → [Apps] → Select specific app  → [Permissions], we can set to allow/disallow apps to use permissions one by one. It becomes more customizable, (I fell it too complicated though).

Security patch

Other than the Android software version update, it seems there’s a Android security patch update frequently.

So far, the big change I can find from user point of view is only these stuffs. Followings are the minor changes.

Boot up animation

Android M boot up animation is different but similar to the Lollipop, 4 balls are interacting animation will be repeated during the boot up.

Hidden game

Google often put some joke implementation in their product. Android is not the exception, it contains a hidden playing game. Go to [Settings] → [About] → press [Version] many times, then the game starts. It was almost same with Lollipop, but there’s a change in the obstacle, it is Marshmallow! See How to enable developer mode in Android TV for Lollipop game.

Updating your Nexus Player to Android M 6.0

Android 6.0 Marshmallow Factory Images are released for Nexus 6, Nexus 5, Nexus 9, Nexus 7, Nexus 10, Neus4 and Nexus Player.

I will explain the steps to update software of your Nexus Player to Android M. The steps should be almost similar to other Nexus devices as well. 

Flashing factory image to Nexus Player

Step 0. install adb and fastboot command

This method is for developers since it requires Android SDK tools set up such as, “adb” and “fastboot” command. If you haven’t set up these commands, you can set up by Building adb and fastboot command from AOSP source code. If you feel it trouble some to build adb and fastboot command manually in your PC, see also

Step 1. Download factory image

Download the factory image which you want to flash from Google developer’s page (direct factory image download link here for Nexus Player). “fugu” is the project name for Nexus Player.

Google developer’s page. Android M (version 6.0.0) is now available.

After downloading, extract it.

tar -xvzf fugu-mra58k-factory-61ac65bc.tgz

Step 2. Boot Nexus Player in bootloader mode

Boot up Nexus Player as usual, connect PC with adb, then reboot it with bootloader mode by

adb reboot bootloader

Bootloader mode on Nexus Player looks like this,

Step 3. Unlock bootloader

First check your fastboot is detecting device correctly or not by checking 

fastboot devices

If it is not working, see bottom page of Building adb and fastboot command from AOSP source code. You can unlock bootloader by 

fastboot oem unlock

I needed to execute command twice to get device unlocked.

~/workspaces/download/fugu-mra58k$ fastboot oem unlock
...
FAILED (remote: To confirm, send the unlock command one more time)
finished. total time: 0.611s
~/workspaces/download/fugu-mra58k$
~/workspaces/download/fugu-mra58k$ fastboot oem unlock
...
OKAY [ 10.089s]
finished. total time: 10.089s

Step 4. Flash factory image

Finally we can flash factory image by

$ cd fugu-mra58k/
$ ./flash-all.sh

Extracted file contains flash-all.sh script, so we can use it to flash factory image. It takes few minutes to automatically flash new factory image (please be careful that all previous user data will be lost!).

Step 5. Run! & Check version.

If factory image was successfully flashed, initial setup will start.

After initial setup, you can check your software version by [Home] → [Settings] → [About]. Android Marshmallow is Version 6.0, you can also check Build number is “MRA58K” for Nexus Player.

I also noticed the new category “Android security patch level” is introduced in Android M.

Ref: Android Now Shows Your Device’s “Android Security Patch Level” In Marshmallow

OTA

For non-developer, it is more easy to update software by OTA.

Reference

Building adb and fastboot command from AOSP source code

adb, android debugging brige, is used for connecting your PC and Android devices to get log, send command to Android devices etc which is very useful for Android software development.

fastboot command is used to control bootloader mode for Nexus devices, it can be used to flash new factory image etc.

Here the method of how to build adb command and fastboot command manually from Android Open Source Project source code is written. If you feel it trouble some to build adb and fastboot command manually in your PC, see also

I used Linux OS (Ubuntu 14.4) for following set up.

Step 1. Build Environment setup

If your PC does not have building environment for AOSP yet, you can set up by just following Establishing a Build Environment.

Step 2. Downloading AOSP Source code

Follow Downloading the Source.

Step 3. Build adb and fastboot

Go to your source code root directory, and set up build environment by

$ source build/envsetup.sh (or $ . build/envsetup.sh)
$ lunch

After lunch command, following will appear so that you can choose your buildtype.

~/workspaces/aosp$ lunch

You're building on Linux

Lunch menu... pick a combo:
1. aosp_arm-eng
2. aosp_arm64-eng
3. aosp_mips-eng
4. aosp_mips64-eng
5. aosp_x86-eng
6. aosp_x86_64-eng
7. aosp_deb-userdebug
8. aosp_flo-userdebug
9. full_fugu-userdebug
10. aosp_fugu-userdebug
11. aosp_grouper-userdebug
12. aosp_tilapia-userdebug
13. mini_emulator_arm64-userdebug
14. m_e_arm-userdebug
15. mini_emulator_mips-userdebug
16. mini_emulator_x86_64-userdebug
17. mini_emulator_x86-userdebug
18. aosp_flounder-userdebug
19. aosp_hammerhead-userdebug
20. aosp_mako-userdebug
21. aosp_shamu-userdebug
22. aosp_manta-userdebug

Which would you like? [aosp_arm-eng]

You can type number and press enter to proceed. In my case, I want to build for Nexus Player so I chose 10 (aosp_fugu-userdebug). 

Finally we can build by

$ make adb fastboot

make will takes several minutes to build adb and fastboot.

Step 4. Adding a environment path

Immediately after building, you can find these command by,

$ which fastboot
~/workspaces/aosp/out/host/linux-x86/bin//fastboot
$ which adb
~/workspaces/aosp/out/host/linux-x86/bin//adb

It is better to set environment path (because after this log in session finishes, this path setting will be removed).

# Environment path setting for adb & fastboot
export PATH=~/workspaces/aosp/out/host/linux-x86/bin/:$PATH

Step 5. Check function

Finally you can check if fastboot and adb is working correctly or not.  

adb

First is to check adb, connect your PC and Android device by USB. Enable developer mode for your Android device, and after enable USB debugging, type 

$ adb devices

It should show device which PC is connecting to. Try sudo if it is not working.

fastboot

Finally check fastboot. Reboot your Nexus devices with bootloader mode

$ adb reboot bootloader

After Nexus reboots with bootloader mode, type

$ fastboot devices
XXXXXXXX fastboot

and check if you can see devices or not. try sudo if it is not working, or it says “waiting for devices” forever. If fastboot is not working, you may need to set up Android device udev rules (refer below links).

Reference

AsyncTask implementation framework – to be independent from Activity –

Continuing from AsyncTask usage summary. Interest is how to establish independence between Activity and AsyncTask? The answer is well summarized in the article, Android AsyncTask はバックグラウンドの処理に集中すべし!”. I will just translate and re-summarize this article. 3 ways will be introduced. 

Advance – implementation framework of AsyncTask

A. Define as inner class of Activity

Most intuitive, easy and faster way is to implement your AsyncTask inside Activity which use it. It is nice choice when CustomAsyncTask is specific (highly dependent on) to the parent Activity.

Mock implementation is like below, here text of mEditText is updated after AsyncTask’s background process.

public class SomeActivity extends Activity {

    private static final String TAG = SomeActivity.class.getSimpleName();
    private EditText mEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mEditText = (EditText) findViewById(R.id.edit_text);

        (new CustomAsyncTask()).execute();
    }

    public class CustomAsyncTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            String result = null;

            // background process

            return result;
        }

        protected void onPostExecute(String result) {
            // Update Activity UI here
            mEditText.setText(result);
        }
    }
}

The problem is that member of Activity, mEditText, is used inside onPostExecute() method of CustomAsyncTask. So this is basically only applicable for this Activity. To separate the work of common AsyncTask part and Activity’s UI update part, we can take following methods. One way is to override methods at Activity, the other way is to implement custom callback.

B. Override UI thread task at Activity side

Consider like this. AsyncTask should concentrate on background task, Activity side will do all UI update task. We can achieve it by overriding UI thread task (onPreExecute, onProgressUpdate and onPostExecute) at Activity. 

Mock implementation 

public class SomeActivity extends Activity {

    private static final String TAG = SomeActivity.class.getSimpleName();
    private EditText mEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mEditText = (EditText) findViewById(R.id.edit_text);

        new CustomAsyncTask(){
            // Override UI thread methods in Activity 
            @Override
            protected void onPostExecute(String result) {
                // Update Activity UI here
                mEditText.setText(result);
            }
        }.execute();
    }
}
    public class CustomAsyncTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            String result = null;

            // background process

            return result;
        }
    }

As you can see, CustomAsyncTask only implements doInBackground() method. All other UI update method is implemented in Activity (caller) side. It is a tricky implementation, but it enables us to divide the role of AsyncTask and Activity. 

One concern is it has less encapsulation (basically, Activity side can do any UI update based on the result). No common behavior of onPostExecute() is implemented in AsyncTask side, This implementaton may differ among Activities.

C. Register callback to invoke Activity method

The last, most organized way to make AsyncTask independent from Activity is to implement callback. We can reduce dependency between Activity and AsyncTask, but you need to take care about designing callback method types. 

Callback methods are implemented as interface in below mock implementation.

import android.os.AsyncTask;

/**
 * AsyncTask<Params, Progress, Result>
 *     Params:   Input parameter type
 *        - arg of {@link #doInBackground}
 *
 *     Progress: Progress parameter type
 *        - arg of {@link #onProgressUpdate}
 *
 *     Result:   Return parameter from background process
 *        - return type of {@link #doInBackground}
 *        - arg of {@link #onPostExecute}
 */
public class CustomAsyncTask extends AsyncTask<Void, Void, String> {

    private static final String TAG = CustomAsyncTask.class.getSimpleName();
    private CustomAsyncTaskCallback mCallback = null;

    public CustomAsyncTask(CustomAsyncTaskCallback callback) {
        mCallback = callback;
    }

    @Override
    protected void onPreExecute() {
        // Initial UI set up here (if necessary)

        if(mCallback != null){
            mCallback.onPreExecute();
        }
    }

    @Override
    protected String doInBackground(Void... params) {
        String result = null;
        // Implement (maybe long) background process here!
        return result;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        // invoked when publishProgress() is called,
    }

    @Override
    protected void onPostExecute(String result) {
        // Finally, the result of doInBackground is handled on UI thread here.

        if(mCallback != null){
            mCallback.onPostExecute(result);
        }
    }

    /** Interface for Activity callback */
    public interface CustomAsyncTaskCallback {
        void onPreExecute();
        void onPostExecute(String result);
        /* Add other callback method if necessary */
        // void onProgressUpdate();
    }
}

To use this callbacks at Activity side, Activity can implement this callback interface. Then, we can implement the function of this callback at Activity side to update UI.  

public class SomeActivity extends Activity implements CustomAsyncTask.CustomAsyncTaskCallback {

    private static final String TAG = SomeActivity.class.getSimpleName();

    private EditText mEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mEditText = (EditText) findViewById(R.id.edit_text);

        new CustomAsyncTask(this).execute();
    }

    /** CustomAsyncTaskCallback interface implementation */
    @Override
    public void onPreExecute() {
        // This callback is invoked from CustomAsyncTask.onPreExecute()
    }

    /** CustomAsyncTaskCallback interface implementation */
    @Override
    public void onPostExecute(String result) {
        // This callback is invoked from CustomAsyncTask.onPostExecute()
        mEditText.setText(result);
    }
}

Summary table

 A. Inner class implementationB. Override UI thread methodsC. Callback implementation
Independent from Activity?
ProsEasyFastFasterFlexibleMost organized
ConsThe AsyncTask is only for parent ActivityTricky Haphazard Strict design is neededTroublesome

Conclusion – which way to use?

  • Implementation speed is more important. (First implementation, debugging etc)
  • It is ok that the CustomAsyncTask is only for specific Activity
    → A. Implement as inner class of Activity
  • Personal, small team project.
  • Faster, more flexible, unplanned implementation.
    → B. Override UI thread task from Activity side
  • Official, team project.
  • Specification is designed concretely.
    → C. Use callback at Activity side

* This is just a personal opinion. Please find yourself which method to adopt for your project.

Reference

Android Studio Live Templates Usage Examples

Android Studio, IDE offered by JetBrain, helps your day if you know how to use it more and more. Continuing from live template introduction, I introduce some examples of custom live templates which I found it convenient to use during my Android app development. To add your custom live template go to [File] → [Settings] → Select [Editor] category, [Leve Templates] → On the right side, you can add your custom template to “user” category. Click + button → [1. Live Templates].

1. dump – check variables value for debugging

  • Abbreviation: dump
  • Description: print log to check variable’s value
  • Template text:
Log.v(TAG, "$VARIABLE$: " + $VARIABLE$);
  • Set applicable contexts to “Java” language.

Template variables

It is useful when you want to check variable’s value for debugging. Here $VARIABLE$ (You can use other than the name “VARIABLE” as well, just need to pinch with $, like  $<variable_name>$.) can be used a variable which user specify after extracting this template.

Type “dump” and then press [tab], you can write both string of variable and real variable at the same time.

2. tag – class TAG definition to be used for logcat log.

  • Abbreviation: tag
  • Description: Class tag definition declaration
  • Template text:
private static final String TAG = $className$.class.getSimpleName();
  • Set applicable contexts to “Java” language.

Predefined functions in live template variables

Also specify $className$ by click [Edit variables], and choose Expression as className()

By choosing the Expression variable $className$ will be expanded automatically, in this case with class name.

For the Android app development, we use logcat as a debug printing system, and we always need to specify “TAG” to use logcat. Therefore, this declaration can be used quite often.

Type “tag” and then press [tab], it will expand a TAG declaration according to the current Class name.

3. try – catch structure writing

  • Abbreviation: try
  • Description: try – catch statement
  • Template text:
try {
    $END$
} catch (Exception e) {
    MLog.e(TAG, e.toString());
}
  • Set applicable contexts to “Java” language.

It can be used as Java common template, no need to explain this is exactly the “template” we often write.

Predefined live template variables

Here, $END$ has a special meaning. The 2 variable, $END$ and $SELECTION$, are called predefined live template variables. These are treated as special and cannot be used for user-define template variables. 

$END$ indicates the position of the cursor after the template is expanded.

$SELECTION$ is used in surround templates and stands for the code fragment to be wrapped. After the template is expanded, the selected text is wrapped as specified in the template.

Cite from IntelliJ IDEA 14.1.0 Help

For the catch statement, it is better to catch specific Exception instead of getting general Exception as shown here. But when you want to write code faster, or personal project, it might be a good choice to just expand default try – catch statement.

Using default value in variable

You can set default value of variable by setting it to “expression” column. For example, if you want to set default_value, you need to write “default_value” in expression column, and press enter. Note that you need to surround the value with double quotation “”.

Note that Reference