Android Misc

android hack's handbook


Java Usage example: myMenuItem.setIcon(android.R.drawable.ic_menu_save);
Resource Usage example: android:icon="@android:drawable/ic_menu_save"

memory leak


sudo apt-get install python2.7

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java6-installer

sudo apt-get install openjdk-6-jdk

sudo apt-get install git gnupg flex bison gperf build-essential zip curl libc6-dev libncurses5-dev:i386 x11proto-core-dev libx11-dev:i386 libreadline6-dev:i386 libglapi-mesa:i386 libgl1-mesa-glx:i386 libgl1-mesa-dev g++-multilib mingw32 tofrodos python-markdown libxml2-utils xsltproc zlib1g-dev:i386

sudo ln -s /usr/lib/i386-linux-gnu/mesa/ /usr/lib/i386-linux-gnu/

nano /etc/udev/rules.d/51-android.rules

export USE_CCACHE=1
export CCACHE_DIR=/home/master/cache
export OUT_DIR_COMMON_BASE=/home/master/output
export PATH=/home/master/bin:$PATH

curl > ~/bin/repo
chmod a+x ~/bin/repo

prebuilts/misc/linux-x86/ccache/ccache -M 50G

cd ~/work
repo init -u -b android-4.3_r1.1
repo sync

export ANDROID_PRODUCT_OUT=/home/master/output/work/target/product/maguro

~/output/work/host/linux-x86/bin/adb reboot bootloader
~/output/work/host/linux-x86/bin/adb flashall -w

cp ~/output/work/target/product/maguro/boot.img .
mkdir /tmp/b
cd tmp/b
sudo apt-get install abootimg
abootimg -x boot.img

ls -l
nano ./bootimg.cfg
abootimg —create myboot.img -f boot.cfg -k ~/work/device/samsung/tuna/omap/arch/arm/boot/zImage -r initrd.img
abootimg —create myboot.img -f bootimg.cfg -k ~/work/device/samsung/tuna/omap/arch/arm/boot/zImage -r initrd.img
~/output/work/host/linux-x86/bin/fastboot boot myboot.img

good tutorial

another way:
cp ~/work/device/samsung/tuna/omap/arch/arm/boot/zImage ~/work/device/samsung/tuna/kernel
then build ROM!msg/android-building/qzSxFEqWvNg/qanfxMkzXHMJ

The Galaxy Nexus family is codenamed "tuna". Using fish names in
relationship to devices isn't quite new, since in the past we've had
goldfish (emulator), trout (G1), mahimahi (Nexus One), herring (Nexus
S) and stingray (Xoom).

There are two actual Galaxy Nexus devices, codenamed maguro and toro.
Maguro is the GSM/HSPA+ variant, and Toro is the CDMA/LTE variant.
Toro is a bit fatter, hence its name.

In the source tree released yesterday, there are two directories
called device/samsung/tuna and device/samsung/maguro. The former
contains all the files that are common to both toro and maguro, while
the latter contains the maguro-specific files. There's no
device/samsung/toro in AOSP yet, that directory will get created when
we release the exact code that actually ships on toro.

emulator debug

catch crash


adb logcat

This is how to use grep properly:

adb shell logcat | grep -E "tag1|tag2"

Or you could just use logcat's built-in filters:

adb logcat -s "browser","webkit"
adb logcat -s tag1:* tag2:*

Another option is setting the log levels for specific tags:

adb logcat SensorService:S PowerManagerService:S NfcService:S power:I Sensors:E

adb logcat ActivityManager:I MyApp:D *:S

The final element in the above expression, *:S, sets the priority level for all tags to "silent", thus ensuring only log messages with "View" and "MyApp" are displayed.

adb logcat -v threadtime
adb logcat -f /tmp/a.txt // redirect to a file

how to filter by package name:

adb [-s DEVICE_ID] shell ps | head -n 1

it will show the column of PID, Numbering starts from 1. normally it should be 2. if it is not 2, you can then replace print $2 with print $column_pid in the next code snippet.
adb -e logcat | grep $(adb shell ps | grep | awk -F" " ' {print $2}') | egrep -v 'Unexpected value from nativeGetEnabledTags|eglSurfaceAttrib not implemented|IInputConnectionWrapper|IInputConnectionWrapper|dalvikvm'


adb logcat | grep `adb shell ps | grep com.example.package | cut -c10-15`
$ adb shell
$ logcat --help
Usage: logcat [options] [filterspecs]
options include:
  -s              Set default filter to silent.
                  Like specifying filterspec '*:s'
  -f <filename>   Log to file. Default to stdout
  -r [<kbytes>]   Rotate log every kbytes. (16 if unspecified). Requires -f
  -n <count>      Sets max number of rotated logs to <count>, default 4
  -v <format>     Sets the log print format, where <format> is one of:

                  brief process tag thread raw time threadtime long

  -c              clear (flush) the entire log and exit
  -d              dump the log and then exit (don't block)
  -g              get the size of the log's ring buffer and exit
  -b <buffer>     request alternate ring buffer
                  ('main' (default), 'radio', 'events')
  -B              output the log in binary
filterspecs are a series of

where <tag> is a log component tag (or * for all) and priority is:
  V    Verbose
  D    Debug
  I    Info
  W    Warn
  E    Error
  F    Fatal
  S    Silent (highest priority, on which nothing is ever printed)

'*' means '*:d' and <tag> by itself means <tag>:v

If not specified on the commandline, filterspec is set from ANDROID_LOG_TAGS.
If no filterspec is found, filter defaults to '*:I'

If not specified with -v, format is set from ANDROID_PRINTF_LOG
or defaults to "brief"

with grep:

display exception: adb logcat -b main AndroidRuntime:E *:S
life cycle of an app: adb logcat ActivityManager:V *:S
dump events adb logcat -b events *:V
To dump all log entries from "dalvikvm (the Java Virtual Machine)": adb logcat dalvikvm:V *:S

To show all data elements of the log entry with the "-v long" format: adb logcat -v long

dynamic log


eventlog analysis





Press Alt + Enter (Option + Enter on Mac) to accept the quick fix.

Alt+Enter is a shortcut for Quick fix in Android Studio
For Mac: CTRL+J

android:textColor="@android:color/opaque_red"   <-- android defined color
android:textColor="@color/opaque_red"         <-- my defined color
android:textColor="?android:textColorSecondary"   <--- style in current theme, it is the same as: android:attr/textColorSecondary
android:text="@string/hello_world"  <-- my defined string

in style.xml, another usage:

<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">

How to handle rotation

content provider checks read permission


void grantUriPermission
void grantUriPermissionUncheckedLocked()

public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {

public void returnPickerResult(Intent intent) {
0577         intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
0578         setResult(RESULT_OK, intent);
0579         finish();
0580     }

// last chance, check against any uri grants
        if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION)
                == PERMISSION_GRANTED) {

SINGLE—TASK( 简 称 S T ) 和 SINGLE_INSTANCE( 简 称 S I ) 的相同点在于,如果目标 Activity
不存在,则两者都会创建一个新的Task,而如果目标Activity存在,则两者都会切换到已有的Task , 并
终止目标Activity上面的所有Activity,并从 Activity处开始执行。
ST 和 S I 的区别有两点:第一,调用者本身如果是S I , 那么肯定会创建一个新的Task ,无论目标
Activity是否存在,但对于 ST,就没有这么 “ 极端”;第二,S I所在的 Task只会有一个Activity对象,
就是这个SI,而 ST 中可以包含多个A ctivity。

7 如果上一步发现可以从History中 HistoryRecord对象,如果找不到,则先判断是否需要添加一个新的Task ,
- 如果需要则创建,并把指定的 Activity 添加到新Task中;
- 如果不需要创建一个新的Task ,那么就在当前的Task中添加目标HistoryRecord。
• FLAG—ACTIVITY_CLEAR—T O P : 如果指定的Activity已经存在,则清空其上面的Activity。

• android : launchMode=standard / singleTop / singleTask / singleInstance
• androidxlearTaskOnLaunch ^true / false
• android: finishonTaskLaunch=true / false
• android : allowTaskReparent=true / false
成 在 Task之 切 换 ,第二类是为了完成在当前Task中改变Activity的顺序,第三类是为了在Task切换
时 Task内部自动重排所属的Activity。首先来看第一类。
第一类•• 在 Task之间切换。如上面例子,系统允许程序从B 任务切换到C 任务,具体实现就是在
启动的 intent中设置 FLAG—ACTIVITY—NEW_TASK。如 果 intent所匹配到的Activity已经存在于已有
的 Task中,那么就切换T ask(and clear all activities that are on top of the target activity);如果没有,则创建一个新的Task 。而这只是一种实现方式,实际的需求
对于后者,则使用 launchMode来完成,如 图 10 - 6 所示。

• CLEAR_TOP,作用是清除目标Activity上面的 Activity。比如 C 1 -C 2 -C 3 ,如果此时要启动C2,
结果将是C1-C 2,C 3 会被结束掉。
• REORDER_TO_FRONT,简单重排,结果会是 C 1 -C 3 -C 2 。
• NO—HISTORY,目标 Activity不出现在 mHistory中。比如、 C 1-C 2,此时如果要启动C3,而在
C 3 中又启动了 C4,那 么 mHistory中将会是C 1 -C 2 -C 4 ,C 4 返回将从 C 2 处继续执行。

第三类:允许被调 Task在启动前主动重排。首先调用者要发起这个请求,其次是被调者要有这个
功能。发起是通过设置intent标 识 为 RESET_IF_NEEDED实现的,而功能是在 manifest文件中使用
android : clearTaskOnLaunch 和 android : fmishOnTaskLauncli 属性,其具体的作用如其名称所示

public static <T> void executeAsyncTask(AsyncTask<T, ?, ?> asyncTask, T... params) {
        asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License