Android Misc

android hack's handbook

https://archive.org/details/AndroidHackerHandbook
https://ia802305.us.archive.org/19/items/AndroidHackerHandbook/Android%20hacker%20handbook.pdf

button

https://github.com/medyo/Fancybuttons
https://github.com/wasabeef/awesome-android-ui
http://alvinalexander.com/android/android-tutorial-preferencescreen-preferenceactivity-preferencefragment
http://android--code.blogspot.com/
http://stackoverflow.com/questions/24711893/adding-a-click-effect-to-my-button-in-android

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

memory leak

http://www.theshiftingbit.com/Fixing-Memory-Leaks-in-Android-Studio
http://stackoverflow.com/questions/24547555/how-to-analyze-memory-using-android-studio

http://memoryanalyzer.blogspot.com/2008/05/automated-heap-dump-analysis-finding.html
http://scn.sap.com/people/krum.tsvetkov/blog/2007/07/02/finding-memory-leaks-with-sap-memory-analyzer
http://kohlerm.blogspot.com/search/label/memory

http://kohlerm.blogspot.com/2009/07/eclipse-memory-analyzer-10-useful.html

build

http://astro.temple.edu/~tue68607/project/articles/customized-android-aospsystem-nexus4.html
http://astro.temple.edu/~tue68607/resume/articles/customized-android-aospsystem-nexus4.html

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/libGL.so.1 /usr/lib/i386-linux-gnu/libGL.so

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 http://commondatastorage.googleapis.com/git-repo-downloads/repo > ~/bin/repo
chmod a+x ~/bin/repo

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

cd ~/work
repo init -u https://android.googlesource.com/platform/manifest -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

http://www.modaco.com/topic/362883-how-to-compile-your-own-android-kernel-in-linux/
http://csidiropoulos.wordpress.com/tag/initrd-img/

good tutorial

http://free-electrons.com/doc/training/android/slides.pdf

another way:
cp ~/work/device/samsung/tuna/omap/arch/arm/boot/zImage ~/work/device/samsung/tuna/kernel
then build ROM

http://wiki.rootzwiki.com/Samsung_Galaxy_Nexus_%28maguro%29

https://groups.google.com/forum/#!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

http://stackoverflow.com/questions/1554099/why-is-the-android-emulator-so-slow
http://lkubaski.wordpress.com/2012/08/15/running-android-on-vmware-player-with-networking-enabled/
http://www.tech-recipes.com/rx/7517/virtual-box-how-to-run-android-os-and-android-apps-on-your-computer-without-a-phone/

catch crash

http://www.intertech.com/Blog/android-handling-the-unexpected/
http://stackoverflow.com/questions/2681499/android-how-to-auto-restart-application-after-its-been-force-closed
http://stackoverflow.com/questions/601503/how-do-i-obtain-crash-data-from-my-android-application

accessibility

https://pankajchunchun.wordpress.com/2013/07/09/capture-toast-or-notification-using-accessibility-service/
http://www.vogella.com/code/ApiDemos/src/com/example/android/apis/accessibility/TaskBackService.html
http://www.informit.com/articles/article.aspx?p=2268753&seqNum=4

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

http://developer.android.com/tools/debugging/debugging-log.html

how to filter by package name:
http://stackoverflow.com/questions/6854127/filter-logcat-to-get-only-the-messages-from-my-application-in-android

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 com.example.abc | awk -F" " ' {print $2}') | egrep -v 'Unexpected value from nativeGetEnabledTags|eglSurfaceAttrib not implemented|IInputConnectionWrapper|IInputConnectionWrapper|dalvikvm'

or

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
  <tag>[:priority]

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:
http://www.phonesdevelopers.com/1806618/

http://www.herongyang.com/Android/Debug-adb-logcat-Command-Track-Lifecycle-of-Application.html

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

https://github.com/JakeWharton/pidcat

dynamic log

http://blog.csdn.net/tangmin0719/article/details/8910195

Android-logging-kmc-kobayashi.png

http://www.bkjia.com/Androidjc/754139.html

eventlog analysis
http://elinux.org/Android_Logging_System
http://blog.csdn.net/darkengine/article/details/8477502
http://www.gaozhenhua.cn/index.php/Index/Index/showBlog/id/106
http://www.gaozhenhua.cn/index.php/Index/Index/showBlog/id/102

bugreport
http://www.niwozhi.net/demo_c78_i4405.html

patchrom
http://zlblianbo.blog.163.com/blog/static/235055026201432923745255/

dropboxmanager
http://xiaocong.github.io/blog/2012/11/21/to-introduce-android-dropboxmanager-service/

基于Android4.0.3的各种工具信息整理(共130个)
http://www.verydemo.com/demo_c137_i450.html

http://www.kpbird.com/p/android-dev-tools.html

kTfQV.png

http://stackoverflow.com/questions/16588064/how-do-i-add-a-library-project-to-the-android-studio
http://studio-developers-android.blogspot.com/2013/05/adding-jar-to-project-in-android-studio.html

https://developer.chrome.com/multidevice/webview/gettingstarted
Press Alt + Enter (Option + Enter on Mac) to accept the quick fix.

Alt+Enter is a shortcut for Quick fix in Android Studio
https://developer.android.com/sdk/installing/studio-tips.html

http://stackoverflow.com/questions/16619667/view-method-information-in-android-studio
For Mac: CTRL+J

http://www.linuxtopia.org/online_books/android/devguide/guide/topics/resources/android_resources-i18n_ReferencesToResources.html
http://developer.android.com/guide/topics/resources/accessing-resources.html#ReferencesToThemeAttributes

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

http://stackoverflow.com/questions/8997822/android-efficient-screen-rotation-handling

content provider checks read permission

ProviderInfo
http://osxr.org/android/source/frameworks/base/core/java/android/content/pm/ProviderInfo.java#0058

void grantUriPermission
void grantUriPermissionUncheckedLocked()
mGrantedUriPermissions.

public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {

http://osxr.org/android/source/frameworks/base/services/java/com/android/server/am/ActivityStack.java#3621
final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {

http://osxr.org/android/source/packages/apps/Contacts/src/com/android/contacts/activities/ContactSelectionActivity.java#0577

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

ContentProvider.java

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

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。
如果要在当前Task中添加HistoryRecord对象,则要处理以下两个启动标识,这两个标识仅适用于
已有的Task中包含目标Activity。
• FLAG—ACTIVITY_CLEAR—T O P : 如果指定的Activity已经存在,则清空其上面的Activity。
• FLAG_ACTIVITY_REORDER_TO_FRONT:该标识没有 CLEAR TOP那么严厉,它只是把自己
放到最上面,而不清空其他已有的。

系统提供了两种方式完成以上的切换,第一种是在AndroidManifest.xml文件中声明Activity自身的
启动属性,另一种是在启动时给intent中添加不同的flag。前者包括:
• android : launchMode=standard / singleTop / singleTask / singleInstance
• androidxlearTaskOnLaunch ^true / false
• android: finishonTaskLaunch=true / false
• android : allowTaskReparent=true / false
后者包括:
• Intent.FLAG_ACTIVITY—NEW—TASK
• Intent.FLAG_ACTIVITY_RESET_TASK_IF—NEEDED
• Intent.FLAG_ACTIVITY_CLEAR—TOP
• Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
• Intent.FLAG—ACTIVITY—NO_HISTORY
• Intent.FLAG_ACTIVITY_SINGLE_TOP
这些设置表面上看起来挺复杂,实际上按功能可分为三类,从而理解起来很简单。第一类是为了完
成 在 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 。而这只是一种实现方式,实际的需求
有时是调用者希望被调者出现在一个新的Task中,有时则是被调者要求自己必须在一个新的Task中,
对于后者,则使用 launchMode来完成,如 图 10 - 6 所示。

第二类:在同一个Task中调整Activity的顺序,由于这些FLAG是用于在当前Task中切换的,因
此不能和NEW—TASK标识一起使用。这类常见的包括以下几种。
• 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 属性,其具体的作用如其名称所示

http://mobile-app-developer.blogspot.com/2012/09/kill-android-asynctask-if-it-hangs.html

http://stackoverflow.com/questions/2018263/android-logging
http://stackoverflow.com/questions/8445667/naming-asynctask-for-profiling-in-android

http://stackoverflow.com/questions/4068984/running-multiple-asynctasks-at-the-same-time-not-possible

@TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11
public static <T> void executeAsyncTask(AsyncTask<T, ?, ?> asyncTask, T... params) {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
    else
        asyncTask.execute(params);
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License