android 技巧



技巧篇

这里记录一些为分类的技巧

遇到ANR的解决方案

    adb pull /data/anr/traces.txt .

通过上面的命令,得到anr详细信息。可以从中找到线索解决这个问题。

adb 获取设备信息

adb shell getprop

adb shell dumpsys window | grep DisplayWidth

如何控制Activity的显示大小及位置?

通常情况下activity会覆盖整个屏幕,有时候我们需要控制activity的大小及显示位置,比如我们把一个activity设置为 “Theme.Dialog” 主题,同时希望其显示位置及大小也随我们控制。 可以通过下面在activity的 onCreate方法中加入以下代码满足我们的要求。 注:下面的代码必须放置在setContentView()方法之后。

    WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
 
        LayoutParams p = getWindow().getAttributes();  //获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 0.6);   //高度设置为屏幕的0.6
        p.width = (int) (d.getWidth() * 0.95);    //宽度设置为屏幕的0.95
        //p.x = 20;  设置顶点坐标
                //p.y= 30;
        getWindow().setAttributes(p);     //设置生效

如何弹出选择默认应用的对话框?

ResolverActivity默认浏览器

弹出所有支持的浏览器

                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                intent.addCategory(Intent.CATEGORY_BROWSABLE);
                Uri content_url = Uri.parse("http://3g.sina.cn");
                intent.setData(content_url);
                ComponentName com = new ComponentName("android",
                        "com.android.internal.app.ResolverActivity");
                intent.setComponent(com);

按包名过滤logcat调试信息

#!/bin/bash
packageName=$1
pid=`adb shell ps | grep $packageName | awk '{print $2}'`
adb logcat | grep --color=auto $pid

使用系统提供的组件进行截图

关键字:com.android.camera.action.CROP

android 的很多组件提供非常松散的调用,下面通过Intent实现截取图片的功能。

final Intent intent = new Intent("com.android.camera.action.CROP");
intent.setClassName("com.android.camera", "com.android.camera.CropImage");
intent.setData(Uri.fromFile(mFile));
intent.putExtra("outputX", width);
intent.putExtra("outputY", height);
intent.putExtra("aspectX", width);
intent.putExtra("aspectY", height);
intent.putExtra("scale", true);
intent.putExtra("noFaceDetection", true);
intent.putExtra("output", Uri.parse("file:/" + mFile.getAbsolutePath()));
startActivityForResult(intent, REQUEST_CROP_IMAGE);

如何使输入键盘不遮挡输入内容?

可以通过“ android:windowSoftInputMode“ 属性来控制输入键盘和输入窗口

android:windowSoftInputMode=“adjustPan” 显示输入键盘不调整主视图的大小

android:windowSoftInputMode=“adjustResize” 该Activity主窗口总是被调整屏幕的大小以便留出软键盘的空间(主视图会被挤上去)

示例:

<activity android:name=".MxBrowserActivity"
            android:launchMode="singleTask" android:alwaysRetainTaskState="true"
            android:windowSoftInputMode="adjustPan" android:label="@string/app_name"
            android:configChanges="orientation|keyboardHidden">

如何获取系统已经安装组件的列表?

 PackageManager packageManager = this.getPackageManager();
List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(0);

如何获取支持分享的组件列表?

     List<ResolveInfo> mApps = new ArrayList<ResolveInfo>();
     Intent intent=new Intent(Intent.ACTION_SEND,null);
     intent.addCategory(Intent.CATEGORY_DEFAULT);
     intent.setType("text/plain");
     PackageManager pManager = context.getPackageManager();
     mApps = pManager.queryIntentActivities(intent,PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
 
     return mApps;

如何判断程序启动是从最近任务列表(长按home键)开始?

有时我们需要知道程序被启动是从luncher还是从最近任务列表启动可以使用以下方法

intent来自桌面或最近任务列表

        final int flags = intent.getFlags();
        String action = intent.getAction();
       if (Intent.ACTION_MAIN.equals(action) ||(flags &   Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY)  = 0) {
 
        }

Android UI 优化 使用<include/>和 <merge />标签

使用<include /> 标签来重用layout代码 如果在一个项目中需要用到相同的布局设计,可以通过<include /> 标签来重用layout代码,该标签在android开发文档中没有相关的介绍。在android主屏程序中 用到了这个标签:

<com.android.launcher.Workspace
  android:id="@+id/workspace"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  launcher:defaultScreen="1">
  <include android:id="@+id/cell1" layout="@layout/workspace_screen" />
  <include android:id="@+id/cell2" layout="@layout/workspace_screen" />
  <include android:id="@+id/cell3" layout="@layout/workspace_screen" />
 
</com.android.launcher.Workspace>

这样可以多次引用一个布局片段而不用重复的复制、粘贴。通过include标签也可以覆写一些属性的值,例如上面的示例就覆写了引用的layout中的id值。下面是另外一个示例:

<include android:layout_width="fill_parent" layout="@layout/image_holder" />
<include android:layout_width="256dip" layout="@layout/image_holder" />

使用<merge /> 标签来减少视图层级结构,在Android layout文件中需要一个顶级容器来容纳其他的组件,而不能直接放置多个组件,例如如下的代码:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="center"
        android:src="@drawable/golden_gate" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Golden Gate" />
</FrameLayout>

单独将<merge />标签做个介绍,是因为它在优化UI结构时起到很重要的作用。目的是通过删减多余或者额外的层级,从而优化整个Android Layout的结构。 将通过一个例子来了解这个标签实际所产生的作用,这样可以更直观的了解<merge/>的用法。 建立一个简单的Layout,其中包含两个Views元素:ImageView和TextView 默认状态下我们将这两个元素放在FrameLayout中。其效果是在主视图中全屏显示一张图片,之后将标题显示在图片上,并位于视图的下方。以下是xml代码:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
 
    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
 
        android:scaleType="center"
        android:src="@drawable/golden_gate" />
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dip"
        android:layout_gravity="center_horizontal|bottom"
 
        android:padding="12dip"
 
        android:background="#AA000000"
        android:textColor="#ffffffff"
 
        android:text="Golden Gate" />
 
</FrameLayout>

应用上边的Layout运行的视图为:

启动 tools> hierarchyviewer.bat工具查看当前UI结构视图:

我们可以很明显的看到由红色线框所包含的结构出现了两个framelayout节点,很明显这两个完全意义相同的节点造成了资源浪费(这里可以提醒大家在开发工程中可以习惯性的通过hierarchyViewer查看当前UI资源的分配情况),那么如何才能解决这种问题呢(就当前例子是如何去掉多余的frameLayout节点)?这时候就要用到<merge />标签来处理类似的问题了。我们将上边xml代码中的framLayout替换成merge:

<merge xmlns:android="http://schemas.android.com/apk/res/android">
 
    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
 
        android:scaleType="center"
        android:src="@drawable/golden_gate" />
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dip"
        android:layout_gravity="center_horizontal|bottom"
 
        android:padding="12dip"
 
        android:background="#AA000000"
        android:textColor="#ffffffff"
 
        android:text="Golden Gate" />
 
</merge>

运行程序后在Emulator中显示的效果是一样的,可是通过hierarchyviewer查看的UI结构是有变化的,当初多余的FrameLayout节点被合并在一起了,或者可以理解为将merge标签中的子集直接加到Activity的FrameLayout跟节点下(这里需要提醒大家注意:所有的Activity视图的根节点都是frameLayout)。如果你所创建的Layout并不是用framLayout作为根节点(而是应用LinerLayout等定义root标签),就不能应用上边的例子通过merge来优化UI结构。

除了上边的例子外,meger还有另外一个用法,当应用Include或者ViewStub标签从外部导入xml结构时,可以将被导入的xml用merge作为根节点表示,这样当被嵌入父级结构中后可以很好的将它所包含的子集融合到父级结构中,而不会出现冗余的节点。

另外有两点需要特别注意:

<merge />只可以作为xml layout的根节点。 当需要扩充的xml layout本身是由merge作为根节点的话,需要将被导入的xml layout置于 viewGroup中,同时需要设置attachToRoot为True。(更多说明请参见inflate()文档)

如何调用系统浏览器打开一个网址?

am start -a android.intent.action.VIEW -d http://www.xiashou.net

如何通过命令行启动一个程序

adb shell am start -n com.google.android.contacts/.ContactsActivity

如何指定设备和模拟器

指定安装在真实设备

adb -d install abc.apk

指定安装在模拟器

adb -e install abc.apk

查看bug

adb bugreport

查看内核日志信息

adb shell dmesg

如何通过xml布局文件构建一个自定义的类?

对于public 属性的 类存在两种形式:

1

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:orientation="vertical"
    >
        <view class="com.test.MyView"
            android:id="@+id/myview"
            android:layout_height="5dip"
            android:layout_width="fill_parent"
 
            />
</LinearLayout>

2

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:orientation="vertical"
    >
        <com.test.MyView
            android:id="@+id/myview"
            android:layout_height="5dip"
            android:layout_width="fill_parent"
 
            />
</LinearLayout>

对于内部类我们可以采用下面的形式从布局文件构造

<!-- 其中SubView是MyView的子类-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:orientation="vertical"
    >
        <view class="com.test.MyView$SubView"
            android:id="@+id/SubView"
            android:layout_height="5dip"
            android:layout_width="fill_parent"
            />
</LinearLayout>

自定义视图代码结构如下

class MyClass extend View
{
   private static class SubView extends View {
   }
}

通过xml构造绘制一个动态图像

我们可以直接通过xml构造一个动态的Drawable对象,xml描述如下

<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/spinner_black_16"
    android:pivotX="50%"
    android:pivotY="50%"
    android:framesCount="12"
    android:frameDuration="100" />

使用代码如下

mCircularProgress = (Drawable) resources.getDrawable(
                com.android.internal.R.drawable.search_spinner);
//set drawable to view
 
((Animatable) mCircularProgress).start();
((Animatable) mCircularProgress).stop();

相关TAG:AnimationDrawable

 AnimationDrawable

此方式在android 2.1下支持

如何隐藏输入法对话框?

    InputMethodManager imm = (InputMethodManager)
        getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
       imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);

如何阻止编辑框弹出输入法对话框?

editText.setOnTouchListener(new OnTouchListener() {
 
 public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub
    //记住EditText的InputType现在是password
    int inType = editText.getInputType(); // backup the input type
    editText.setInputType(InputType.TYPE_NULL); // disable soft input
    editText.onTouchEvent(event); // call native handler
    editText.setInputType(inType); // restore input type
    editText.setSelection(editText.getText().length());
    return true;
 
    }
 });

ListView更改背景后,移动出现黑色框的修改办法

android:cacheColorHint设置为透明(0x00000000)

获取当前程序进程ID,杀掉进程

int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);

如何动态的改变ImageView的背景?

有时候,我们为了在一个image view中显示不同的图片,往往会使用:

if (条件1) {
    image.setBackground(R.id.xxx1);
} else if (条件2) {
    image.setBackground(R.id.xxx2);
} ...

最近发现可以用另一个简便的方法实现相同的功能 首先,在res/drawable下建立一个xml文件,内容如下

<?xml version="1.0" encoding="utf-8"?>
<level-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:maxLevel="0" android:drawable="@android:color/transparent" />
    <item android:maxLevel="1" android:drawable="@drawable/image_1" />
    <item android:maxLevel="2" android:drawable="@drawable/image_2" />
    <item android:maxLevel="3" android:drawable="@drawable/image_3" />
</level-list>

使用方法:

imageview.getDrawable().setLevel(0) //- 透明
imageview.getDrawable().setLevel(1) // - 显示image_1

android系统中用于显示电量的用法

<level-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:maxLevel="29" android:drawable="@android:drawable/battery_charge_fill_empty" />
    <item android:maxLevel="49" android:drawable="@android:drawable/battery_charge_fill_warning" />
    <item android:maxLevel="100" android:drawable="@android:drawable/battery_charge_fill_full" />
</level-list>

从一个视图获得该视图的快照

 
		v.buildDrawingCache();
		Bitmap viewBitmap = v.getDrawingCache();

创建自定义属性的方法

自定义属性attrs

1、在 attrs.xml 添加属性定义:

attrs.xml

1:     <declare-styleable name="GestureInflater">
2:         <attr name="id" format="reference" />
3:         <!-- the gesture action name, defined in strings.xml -->
4:         <attr name="title" format="string" />
5:         <!-- the gesture-bitmap name -->
6:         <attr name="name" format="string" />
7:     </declare-styleable>

2、 创建GestureInflater.java类, 用于解析xml文件

GestureInflater.java

 1:     public void inflate(int resId, List<GestureItem> items){
 2:         XmlResourceParser parser = null;
 3:         try {
 4:             parser = mContext.getResources().getLayout(resId);
 5:             AttributeSet attrs = Xml.asAttributeSet(parser);
 6:
 7:             parseXml(parser, attrs, items);
 8:         } catch (XmlPullParserException e) {
 9:             e.printStackTrace();
10:         } catch (IOException e) {
11:             e.printStackTrace();
12:         } finally {
13:             if (parser != null) parser.close();
14:         }
15:     }
16:
17:     private void parseXml(XmlResourceParser parser, AttributeSet attrs, List<GestureItem> items) throws XmlPullParserException, IOException{
18:         int eventType = parser.getEventType();
19:         String tagName;
20:
21:         do {
22:             if (eventType == XmlPullParser.START_TAG) {
23:                 tagName = parser.getName();
24:                 if (tagName.equals("gesture_config")) {
25:                     // Go to next tag
26:                     eventType = parser.next();
27:                     break;
28:                 }
29:
30:                 throw new RuntimeException("Expecting gesture_config, got " + tagName);
31:             }
32:             eventType = parser.next();
33:         } while (eventType != XmlPullParser.END_DOCUMENT);
34:
35:         boolean lookingForEndOfUnknownTag = false;
36:         String unknownTagName = null;
37:         boolean reachedEnd = false;
38:
39:         while (!reachedEnd) {
40:             switch (eventType) {
41:                 case XmlPullParser.START_TAG:
42:                     if (lookingForEndOfUnknownTag) {
43:                         break;
44:                     }
45:
46:                     tagName = parser.getName();
47:                     if (tagName.equals("item")) {
48:                         TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.GestureInflater);
49:                         GestureItem item = new GestureItem();
50:                         item.mId = a.getResourceId(R.styleable.GestureInflater_id, -1);
51:                         item.mTitle = a.getString(R.styleable.GestureInflater_title);
52:                         item.mName = a.getString(R.styleable.GestureInflater_name);
53:
54:                         Log.w("MxBrowser", "gesture id:"+item.mId+"; name="+item.mName+"; title="+item.mTitle);
55:
56:                         items.add(item);
57:                     } else {
58:                         lookingForEndOfUnknownTag = true;
59:                         unknownTagName = tagName;
60:                     }
61:                     break;
62:
63:                 case XmlPullParser.END_TAG:
64:                     tagName = parser.getName();
65:                     if (lookingForEndOfUnknownTag && tagName.equals(unknownTagName)) {
66:                         lookingForEndOfUnknownTag = false;
67:                         unknownTagName = null;
68:                     } else if (tagName.equals("item")) {
69:                         //end item;
70:                     }else if(tagName.equals("gesture_config")){
71:                         reachedEnd = true;
72:                     }
73:                     break;
74:
75:                 case XmlPullParser.END_DOCUMENT:
76:                     throw new RuntimeException("Unexpected end of document");
77:             }
78:
79:             eventType = parser.next();
80:         }
81:     }

3、在res/xml下创建自己的资源

 1: <?xml version="1.0" encoding="utf-8"?>
 2: <gesture_config xmlns:android="http://schemas.android.com/apk/res/android"
 3:     xmlns:gesture_config="http://schemas.android.com/apk/res/com.mx.browser">
 4:
 5:     <item gesture_config:id="@+id/gesture_settings" gesture_config:title="@string/gesture_open_gesture_settings"  gesture_config:name="gestureSettings" />
 6:     <item gesture_config:id="@+id/gesture_open_bookmark" gesture_config:title="@string/gesture_open_bookmark" gesture_config:name="openBookmark" />
 7:     <item gesture_config:id="@+id/gesture_add_bookmark" gesture_config:title="@string/gesture_add_bookmark" gesture_config:name="addBookmark" />
 8:     <item gesture_config:id="@+id/gesture_open_mostvisit" gesture_config:title="@string/gesture_most_visit" gesture_config:name="mostVisit" />
 9:     <item gesture_config:id="@+id/gesture_open_history" gesture_config:title="@string/gesture_open_history" gesture_config:name="openHistory" />
10:     <item gesture_config:id="@+id/gesture_new_tab" gesture_config:title="@string/gesture_new_tab" gesture_config:name="newTab" />
11:     <item gesture_config:id="@+id/gesture_prev_tab" gesture_config:title="@string/gesture_prev_tab" gesture_config:name="prevTab" />
12:     <item gesture_config:id="@+id/gesture_next_tab" gesture_config:title="@string/gesture_next_tab" gesture_config:name="nextTab" />
13:     <item gesture_config:id="@+id/gesture_close_tab" gesture_config:title="@string/gesture_close_tab" gesture_config:name="closeTab" />
14:     <item gesture_config:id="@+id/gesture_backward" gesture_config:title="@string/gesture_backward" gesture_config:name="backward" />
15:     <item gesture_config:id="@+id/gesture_forward" gesture_config:title="@string/gesture_foward" gesture_config:name="forward" />
16:     <item gesture_config:id="@+id/gesture_refresh" gesture_config:title="@string/gesture_refresh" gesture_config:name="refresh" />
17:     <item gesture_config:id="@+id/gesture_find_in_page" gesture_config:title="@string/gesture_find_in_page" gesture_config:name="findInPage" />
18:     <item gesture_config:id="@+id/gesture_select_text" gesture_config:title="@string/gesture_select_text" gesture_config:name="selectText" />
19:     <item gesture_config:id="@+id/gesture_share_url" gesture_config:title="@string/gesture_share_url" gesture_config:name="shareUrl" />
20:
21: </gesture_config>

gestureconfig.xml

这样, 我们就可以像系统组建一样使用我们自己的组建:

example.java

 1: GestureInflater inflater = new GestureInflater(context);
 2: inflater.inflate(R.xml.gestureconfig, ...);
 3: ... ...
 4:
 5: switch(gesture.getID){
 6:     case R.id.gesture_backword:
 7:         goBack();
 8:         break;
 9:
10:      ... ...
11: }

修改Dialog的背景透明度

Dialog dg = new Dialog(this);


Window window = dg.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.alpha = 0.5f;
        window.setAttributes(lp)

让Activity变成一个窗口

 讲点轻松的吧,可能有人希望做出来的应用程序是一个漂浮在手机主界面的东西,那么很

简单你只需要设置 一下Activity的主题就可以了在AndroidManifest.xml 中定义

Activity以对话框的形式弹出

android :theme="@android:style/Theme.Dialog"
android:theme="@android:style/Theme.Dialog"

Activity以半透明的方式弹出

android:theme="@android:style/Theme.Translucent"
android:theme="@android:style/Theme.Translucent"

将中文设置成粗体

在xml文件中使用android:textStyle=”bold” 可以将英文设置成粗体,但是不能将中文设置成粗体, 将中文设置成粗体的方法是: TextView tv = (TextView)findViewById(R.id.TextView01); TextPaint tp = tv.getPaint(); tp.setFakeBoldText(true);

如何在android adt环境下使用第三方java程序?

1. 为第三方java程序生成.jar文件

2. 选择当前android项目→build path→config-build path→Libraries→Add External jars

优化Dalvik虚拟机的堆内存

//用此方法优化gc的效率,参考android源码TARGET_HEAP_UTILIZATION
// 活动的对象的内存/堆的大小
VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION)  //UTILIZATION = 0.75f
 
final static int HEAP_SIZE = 6* 1024* 1024 ;
VMRuntime.getRuntime().setMinimumHeapSize(HEAP_SIZE); //调整堆内存

使用tcpdump在android手机上进行抓包

使用tcpdump在android手机上进行抓包

运行tcpdump具有root权限

  1. 下载tcpdump文件tcpdump文件 tcpdump_001.zip
  2. adb push tcpdump /sdcard/tcpdump 安装文件
  3. adb shell tcpdump -p -vv -s 0 -w /sdcard/capture.pcap来进行抓包
  4. 使用 adb pull /sdcard/capture.pcap获取抓包数据
  5. 使用wireshark来查看抓包数据

使用系统生成的唯一id

在values/ids.xml中定义

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item type="id" name="button_ok" />
    <item type="id" name="dialog_exit" />
</resources>

使用时可以用showDialog(R.id.dialog_exit)

android修改Hosts文件

$su
#mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system
echo "168.143.161.20 twitter.com www.twitter.com" >> /etc/hosts
mount -o remount,ro -t yaffs2 /dev/block/mtdblock3 /system

在处理sqlite转义字符

SQLite转义字符

在 selection 中需要嵌入字符串的地方用 ? 代替,然后在 selectionArgs 中依次提供各个用于替换的值就可以了。在 query() 执行时会对 selectionArgs 中的字符串正确转义并替换到对应的 ? 处以构成完整的 selection 字符串。 有点像 String.format()。

public void doQuery(long id, final String name) {
  mDb.query("some_table", // table name
        null, // columns
        "id=" + id + " AND name=?", // selection
        new String[] {name}, //selectionArgs
         //...... 更多参数省略
  );
  // ...... 更多代码
}
}

如何查看padding和margin

如何向cursor写入数据

如何向一个cursor里添加额外的数据而又不改变数据库里的数据?

You can subclass SQLiteDatabase.CursorFactory to return, from its 
newCursor method, a subclass of SQLiteCursor. This factory gets passed 
to the SQLiteOpenHelper constructor so, when you query it, it will 
return Cursors of your new SQLiteCursor subclass type. 
The SQLiteCursor subclass can then expose methods that manage its 
protected mWindow field, which is a CursorWindow. This object has 
putXxx methods to manipulate the data. 
I haven't tried this myself, so if anyone has any tips or hints, 
please post. 

模拟器修改hosts文件

emulator -avd youravdname -partition-size 128
adb shell ping xx.xx.xx
adb root
adb remount
adb pull /system/etc/hosts /tmp/hosts
echo "192.168.1.32 xx.xx.xx" >> /tmp/hosts
adb push /tmp/hosts /system/etc/hosts
adb shell ping xx.xx.xx

如何获取指定类型的activity 列表 ?

有时候我们需要获取某一类activity的列表,如属性为 Intent.CATEGORY_LAUNCHER (可以启动的应用) 列表. 可以使用以下方法

 Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
 
        PackageManager pm = getPackageManager();
        List<ResolveInfo> list = pm.queryIntentActivities(mainIntent, 0);

发散思维: 我们可以自定义一类activity为我们的主activity服务.比如在插件系统中我们定义一个”com.mx.browser.plugin”的类别.

svn遇到is already under version control 解决办法?

解决办法:以uploads目录为例

删除uploads目录下的.svn目录及下面的文件(保留uploads目录的.svn) #find uploads |grep 'uploads/[^\.]*/.svn'|xargs rm -rf

当发生分支不能合并到主干时怎么办?

  1. 列出自己修改过的类
  2. 使用vimdiff工具,比较这些文件,合并很方便
  3. 检查合并过去的类

需要输入一个很长很长的网址时

  1. 在pc浏览器上输入 http://qrcode.kaywa.com/img.php?s=5&d=加上你的网址
  2. 上面的结果会生成一个二维码,使用手机的二维码识别程序,识别就好了

svn修改账户

删除 eclipse/configuration/org.eclipse.core.runtime/.keyring

点击Dialog外部令Dialog自动消失

设置Dialog.setCanceledOnTouchOutside(true);



技巧篇

这里记录一些为分类的技巧

遇到ANR的解决方案

    adb pull /data/anr/traces.txt .

通过上面的命令,得到anr详细信息。可以从中找到线索解决这个问题。

adb 获取设备信息

adb shell getprop

adb shell dumpsys window | grep DisplayWidth

如何控制Activity的显示大小及位置?

通常情况下activity会覆盖整个屏幕,有时候我们需要控制activity的大小及显示位置,比如我们把一个activity设置为 “Theme.Dialog” 主题,同时希望其显示位置及大小也随我们控制。 可以通过下面在activity的 onCreate方法中加入以下代码满足我们的要求。 注:下面的代码必须放置在setContentView()方法之后。

    WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
 
        LayoutParams p = getWindow().getAttributes();  //获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 0.6);   //高度设置为屏幕的0.6
        p.width = (int) (d.getWidth() * 0.95);    //宽度设置为屏幕的0.95
        //p.x = 20;  设置顶点坐标
                //p.y= 30;
        getWindow().setAttributes(p);     //设置生效

如何弹出选择默认应用的对话框?

ResolverActivity默认浏览器

弹出所有支持的浏览器

                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                intent.addCategory(Intent.CATEGORY_BROWSABLE);
                Uri content_url = Uri.parse("http://3g.sina.cn");
                intent.setData(content_url);
                ComponentName com = new ComponentName("android",
                        "com.android.internal.app.ResolverActivity");
                intent.setComponent(com);

按包名过滤logcat调试信息

#!/bin/bash
packageName=$1
pid=`adb shell ps | grep $packageName | awk '{print $2}'`
adb logcat | grep --color=auto $pid

使用系统提供的组件进行截图

关键字:com.android.camera.action.CROP

android 的很多组件提供非常松散的调用,下面通过Intent实现截取图片的功能。

final Intent intent = new Intent("com.android.camera.action.CROP");
intent.setClassName("com.android.camera", "com.android.camera.CropImage");
intent.setData(Uri.fromFile(mFile));
intent.putExtra("outputX", width);
intent.putExtra("outputY", height);
intent.putExtra("aspectX", width);
intent.putExtra("aspectY", height);
intent.putExtra("scale", true);
intent.putExtra("noFaceDetection", true);
intent.putExtra("output", Uri.parse("file:/" + mFile.getAbsolutePath()));
startActivityForResult(intent, REQUEST_CROP_IMAGE);

如何使输入键盘不遮挡输入内容?

可以通过“ android:windowSoftInputMode“ 属性来控制输入键盘和输入窗口

android:windowSoftInputMode=“adjustPan” 显示输入键盘不调整主视图的大小

android:windowSoftInputMode=“adjustResize” 该Activity主窗口总是被调整屏幕的大小以便留出软键盘的空间(主视图会被挤上去)

示例:

<activity android:name=".MxBrowserActivity"
            android:launchMode="singleTask" android:alwaysRetainTaskState="true"
            android:windowSoftInputMode="adjustPan" android:label="@string/app_name"
            android:configChanges="orientation|keyboardHidden">

如何获取系统已经安装组件的列表?

 PackageManager packageManager = this.getPackageManager();
List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(0);

如何获取支持分享的组件列表?

     List<ResolveInfo> mApps = new ArrayList<ResolveInfo>();
     Intent intent=new Intent(Intent.ACTION_SEND,null);
     intent.addCategory(Intent.CATEGORY_DEFAULT);
     intent.setType("text/plain");
     PackageManager pManager = context.getPackageManager();
     mApps = pManager.queryIntentActivities(intent,PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
 
     return mApps;

如何判断程序启动是从最近任务列表(长按home键)开始?

有时我们需要知道程序被启动是从luncher还是从最近任务列表启动可以使用以下方法

intent来自桌面或最近任务列表

        final int flags = intent.getFlags();
        String action = intent.getAction();
       if (Intent.ACTION_MAIN.equals(action) ||(flags &   Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY)  = 0) {
 
        }

Android UI 优化 使用<include/>和 <merge />标签

使用<include /> 标签来重用layout代码 如果在一个项目中需要用到相同的布局设计,可以通过<include /> 标签来重用layout代码,该标签在android开发文档中没有相关的介绍。在android主屏程序中 用到了这个标签:

<com.android.launcher.Workspace
  android:id="@+id/workspace"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  launcher:defaultScreen="1">
  <include android:id="@+id/cell1" layout="@layout/workspace_screen" />
  <include android:id="@+id/cell2" layout="@layout/workspace_screen" />
  <include android:id="@+id/cell3" layout="@layout/workspace_screen" />
 
</com.android.launcher.Workspace>

这样可以多次引用一个布局片段而不用重复的复制、粘贴。通过include标签也可以覆写一些属性的值,例如上面的示例就覆写了引用的layout中的id值。下面是另外一个示例:

<include android:layout_width="fill_parent" layout="@layout/image_holder" />
<include android:layout_width="256dip" layout="@layout/image_holder" />

使用<merge /> 标签来减少视图层级结构,在Android layout文件中需要一个顶级容器来容纳其他的组件,而不能直接放置多个组件,例如如下的代码:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="center"
        android:src="@drawable/golden_gate" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Golden Gate" />
</FrameLayout>

单独将<merge />标签做个介绍,是因为它在优化UI结构时起到很重要的作用。目的是通过删减多余或者额外的层级,从而优化整个Android Layout的结构。 将通过一个例子来了解这个标签实际所产生的作用,这样可以更直观的了解<merge/>的用法。 建立一个简单的Layout,其中包含两个Views元素:ImageView和TextView 默认状态下我们将这两个元素放在FrameLayout中。其效果是在主视图中全屏显示一张图片,之后将标题显示在图片上,并位于视图的下方。以下是xml代码:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
 
    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
 
        android:scaleType="center"
        android:src="@drawable/golden_gate" />
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dip"
        android:layout_gravity="center_horizontal|bottom"
 
        android:padding="12dip"
 
        android:background="#AA000000"
        android:textColor="#ffffffff"
 
        android:text="Golden Gate" />
 
</FrameLayout>

应用上边的Layout运行的视图为:

启动 tools> hierarchyviewer.bat工具查看当前UI结构视图:

我们可以很明显的看到由红色线框所包含的结构出现了两个framelayout节点,很明显这两个完全意义相同的节点造成了资源浪费(这里可以提醒大家在开发工程中可以习惯性的通过hierarchyViewer查看当前UI资源的分配情况),那么如何才能解决这种问题呢(就当前例子是如何去掉多余的frameLayout节点)?这时候就要用到<merge />标签来处理类似的问题了。我们将上边xml代码中的framLayout替换成merge:

<merge xmlns:android="http://schemas.android.com/apk/res/android">
 
    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
 
        android:scaleType="center"
        android:src="@drawable/golden_gate" />
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dip"
        android:layout_gravity="center_horizontal|bottom"
 
        android:padding="12dip"
 
        android:background="#AA000000"
        android:textColor="#ffffffff"
 
        android:text="Golden Gate" />
 
</merge>

运行程序后在Emulator中显示的效果是一样的,可是通过hierarchyviewer查看的UI结构是有变化的,当初多余的FrameLayout节点被合并在一起了,或者可以理解为将merge标签中的子集直接加到Activity的FrameLayout跟节点下(这里需要提醒大家注意:所有的Activity视图的根节点都是frameLayout)。如果你所创建的Layout并不是用framLayout作为根节点(而是应用LinerLayout等定义root标签),就不能应用上边的例子通过merge来优化UI结构。

除了上边的例子外,meger还有另外一个用法,当应用Include或者ViewStub标签从外部导入xml结构时,可以将被导入的xml用merge作为根节点表示,这样当被嵌入父级结构中后可以很好的将它所包含的子集融合到父级结构中,而不会出现冗余的节点。

另外有两点需要特别注意:

<merge />只可以作为xml layout的根节点。 当需要扩充的xml layout本身是由merge作为根节点的话,需要将被导入的xml layout置于 viewGroup中,同时需要设置attachToRoot为True。(更多说明请参见inflate()文档)

如何调用系统浏览器打开一个网址?

am start -a android.intent.action.VIEW -d http://www.xiashou.net

如何通过命令行启动一个程序

adb shell am start -n com.google.android.contacts/.ContactsActivity

如何指定设备和模拟器

指定安装在真实设备

adb -d install abc.apk

指定安装在模拟器

adb -e install abc.apk

查看bug

adb bugreport

查看内核日志信息

adb shell dmesg

如何通过xml布局文件构建一个自定义的类?

对于public 属性的 类存在两种形式:

1

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:orientation="vertical"
    >
        <view class="com.test.MyView"
            android:id="@+id/myview"
            android:layout_height="5dip"
            android:layout_width="fill_parent"
 
            />
</LinearLayout>

2

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:orientation="vertical"
    >
        <com.test.MyView
            android:id="@+id/myview"
            android:layout_height="5dip"
            android:layout_width="fill_parent"
 
            />
</LinearLayout>

对于内部类我们可以采用下面的形式从布局文件构造

<!-- 其中SubView是MyView的子类-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:orientation="vertical"
    >
        <view class="com.test.MyView$SubView"
            android:id="@+id/SubView"
            android:layout_height="5dip"
            android:layout_width="fill_parent"
            />
</LinearLayout>

自定义视图代码结构如下

class MyClass extend View
{
   private static class SubView extends View {
   }
}

通过xml构造绘制一个动态图像

我们可以直接通过xml构造一个动态的Drawable对象,xml描述如下

<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/spinner_black_16"
    android:pivotX="50%"
    android:pivotY="50%"
    android:framesCount="12"
    android:frameDuration="100" />

使用代码如下

mCircularProgress = (Drawable) resources.getDrawable(
                com.android.internal.R.drawable.search_spinner);
//set drawable to view
 
((Animatable) mCircularProgress).start();
((Animatable) mCircularProgress).stop();

相关TAG:AnimationDrawable

 AnimationDrawable

此方式在android 2.1下支持

如何隐藏输入法对话框?

    InputMethodManager imm = (InputMethodManager)
        getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
       imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);

如何阻止编辑框弹出输入法对话框?

editText.setOnTouchListener(new OnTouchListener() {
 
 public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub
    //记住EditText的InputType现在是password
    int inType = editText.getInputType(); // backup the input type
    editText.setInputType(InputType.TYPE_NULL); // disable soft input
    editText.onTouchEvent(event); // call native handler
    editText.setInputType(inType); // restore input type
    editText.setSelection(editText.getText().length());
    return true;
 
    }
 });

ListView更改背景后,移动出现黑色框的修改办法

android:cacheColorHint设置为透明(0x00000000)

获取当前程序进程ID,杀掉进程

int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);

如何动态的改变ImageView的背景?

有时候,我们为了在一个image view中显示不同的图片,往往会使用:

if (条件1) {
    image.setBackground(R.id.xxx1);
} else if (条件2) {
    image.setBackground(R.id.xxx2);
} ...

最近发现可以用另一个简便的方法实现相同的功能 首先,在res/drawable下建立一个xml文件,内容如下

<?xml version="1.0" encoding="utf-8"?>
<level-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:maxLevel="0" android:drawable="@android:color/transparent" />
    <item android:maxLevel="1" android:drawable="@drawable/image_1" />
    <item android:maxLevel="2" android:drawable="@drawable/image_2" />
    <item android:maxLevel="3" android:drawable="@drawable/image_3" />
</level-list>

使用方法:

imageview.getDrawable().setLevel(0) //- 透明
imageview.getDrawable().setLevel(1) // - 显示image_1

android系统中用于显示电量的用法

<level-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:maxLevel="29" android:drawable="@android:drawable/battery_charge_fill_empty" />
    <item android:maxLevel="49" android:drawable="@android:drawable/battery_charge_fill_warning" />
    <item android:maxLevel="100" android:drawable="@android:drawable/battery_charge_fill_full" />
</level-list>

从一个视图获得该视图的快照

 
		v.buildDrawingCache();
		Bitmap viewBitmap = v.getDrawingCache();

创建自定义属性的方法

自定义属性attrs

1、在 attrs.xml 添加属性定义:

attrs.xml

1:     <declare-styleable name="GestureInflater">
2:         <attr name="id" format="reference" />
3:         <!-- the gesture action name, defined in strings.xml -->
4:         <attr name="title" format="string" />
5:         <!-- the gesture-bitmap name -->
6:         <attr name="name" format="string" />
7:     </declare-styleable>

2、 创建GestureInflater.java类, 用于解析xml文件

GestureInflater.java

 1:     public void inflate(int resId, List<GestureItem> items){
 2:         XmlResourceParser parser = null;
 3:         try {
 4:             parser = mContext.getResources().getLayout(resId);
 5:             AttributeSet attrs = Xml.asAttributeSet(parser);
 6:
 7:             parseXml(parser, attrs, items);
 8:         } catch (XmlPullParserException e) {
 9:             e.printStackTrace();
10:         } catch (IOException e) {
11:             e.printStackTrace();
12:         } finally {
13:             if (parser != null) parser.close();
14:         }
15:     }
16:
17:     private void parseXml(XmlResourceParser parser, AttributeSet attrs, List<GestureItem> items) throws XmlPullParserException, IOException{
18:         int eventType = parser.getEventType();
19:         String tagName;
20:
21:         do {
22:             if (eventType == XmlPullParser.START_TAG) {
23:                 tagName = parser.getName();
24:                 if (tagName.equals("gesture_config")) {
25:                     // Go to next tag
26:                     eventType = parser.next();
27:                     break;
28:                 }
29:
30:                 throw new RuntimeException("Expecting gesture_config, got " + tagName);
31:             }
32:             eventType = parser.next();
33:         } while (eventType != XmlPullParser.END_DOCUMENT);
34:
35:         boolean lookingForEndOfUnknownTag = false;
36:         String unknownTagName = null;
37:         boolean reachedEnd = false;
38:
39:         while (!reachedEnd) {
40:             switch (eventType) {
41:                 case XmlPullParser.START_TAG:
42:                     if (lookingForEndOfUnknownTag) {
43:                         break;
44:                     }
45:
46:                     tagName = parser.getName();
47:                     if (tagName.equals("item")) {
48:                         TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.GestureInflater);
49:                         GestureItem item = new GestureItem();
50:                         item.mId = a.getResourceId(R.styleable.GestureInflater_id, -1);
51:                         item.mTitle = a.getString(R.styleable.GestureInflater_title);
52:                         item.mName = a.getString(R.styleable.GestureInflater_name);
53:
54:                         Log.w("MxBrowser", "gesture id:"+item.mId+"; name="+item.mName+"; title="+item.mTitle);
55:
56:                         items.add(item);
57:                     } else {
58:                         lookingForEndOfUnknownTag = true;
59:                         unknownTagName = tagName;
60:                     }
61:                     break;
62:
63:                 case XmlPullParser.END_TAG:
64:                     tagName = parser.getName();
65:                     if (lookingForEndOfUnknownTag && tagName.equals(unknownTagName)) {
66:                         lookingForEndOfUnknownTag = false;
67:                         unknownTagName = null;
68:                     } else if (tagName.equals("item")) {
69:                         //end item;
70:                     }else if(tagName.equals("gesture_config")){
71:                         reachedEnd = true;
72:                     }
73:                     break;
74:
75:                 case XmlPullParser.END_DOCUMENT:
76:                     throw new RuntimeException("Unexpected end of document");
77:             }
78:
79:             eventType = parser.next();
80:         }
81:     }

3、在res/xml下创建自己的资源

 1: <?xml version="1.0" encoding="utf-8"?>
 2: <gesture_config xmlns:android="http://schemas.android.com/apk/res/android"
 3:     xmlns:gesture_config="http://schemas.android.com/apk/res/com.mx.browser">
 4:
 5:     <item gesture_config:id="@+id/gesture_settings" gesture_config:title="@string/gesture_open_gesture_settings"  gesture_config:name="gestureSettings" />
 6:     <item gesture_config:id="@+id/gesture_open_bookmark" gesture_config:title="@string/gesture_open_bookmark" gesture_config:name="openBookmark" />
 7:     <item gesture_config:id="@+id/gesture_add_bookmark" gesture_config:title="@string/gesture_add_bookmark" gesture_config:name="addBookmark" />
 8:     <item gesture_config:id="@+id/gesture_open_mostvisit" gesture_config:title="@string/gesture_most_visit" gesture_config:name="mostVisit" />
 9:     <item gesture_config:id="@+id/gesture_open_history" gesture_config:title="@string/gesture_open_history" gesture_config:name="openHistory" />
10:     <item gesture_config:id="@+id/gesture_new_tab" gesture_config:title="@string/gesture_new_tab" gesture_config:name="newTab" />
11:     <item gesture_config:id="@+id/gesture_prev_tab" gesture_config:title="@string/gesture_prev_tab" gesture_config:name="prevTab" />
12:     <item gesture_config:id="@+id/gesture_next_tab" gesture_config:title="@string/gesture_next_tab" gesture_config:name="nextTab" />
13:     <item gesture_config:id="@+id/gesture_close_tab" gesture_config:title="@string/gesture_close_tab" gesture_config:name="closeTab" />
14:     <item gesture_config:id="@+id/gesture_backward" gesture_config:title="@string/gesture_backward" gesture_config:name="backward" />
15:     <item gesture_config:id="@+id/gesture_forward" gesture_config:title="@string/gesture_foward" gesture_config:name="forward" />
16:     <item gesture_config:id="@+id/gesture_refresh" gesture_config:title="@string/gesture_refresh" gesture_config:name="refresh" />
17:     <item gesture_config:id="@+id/gesture_find_in_page" gesture_config:title="@string/gesture_find_in_page" gesture_config:name="findInPage" />
18:     <item gesture_config:id="@+id/gesture_select_text" gesture_config:title="@string/gesture_select_text" gesture_config:name="selectText" />
19:     <item gesture_config:id="@+id/gesture_share_url" gesture_config:title="@string/gesture_share_url" gesture_config:name="shareUrl" />
20:
21: </gesture_config>

gestureconfig.xml

这样, 我们就可以像系统组建一样使用我们自己的组建:

example.java

 1: GestureInflater inflater = new GestureInflater(context);
 2: inflater.inflate(R.xml.gestureconfig, ...);
 3: ... ...
 4:
 5: switch(gesture.getID){
 6:     case R.id.gesture_backword:
 7:         goBack();
 8:         break;
 9:
10:      ... ...
11: }

修改Dialog的背景透明度

Dialog dg = new Dialog(this);


Window window = dg.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.alpha = 0.5f;
        window.setAttributes(lp)

让Activity变成一个窗口

 讲点轻松的吧,可能有人希望做出来的应用程序是一个漂浮在手机主界面的东西,那么很

简单你只需要设置 一下Activity的主题就可以了在AndroidManifest.xml 中定义

Activity以对话框的形式弹出

android :theme="@android:style/Theme.Dialog"
android:theme="@android:style/Theme.Dialog"

Activity以半透明的方式弹出

android:theme="@android:style/Theme.Translucent"
android:theme="@android:style/Theme.Translucent"

将中文设置成粗体

在xml文件中使用android:textStyle=”bold” 可以将英文设置成粗体,但是不能将中文设置成粗体, 将中文设置成粗体的方法是: TextView tv = (TextView)findViewById(R.id.TextView01); TextPaint tp = tv.getPaint(); tp.setFakeBoldText(true);

如何在android adt环境下使用第三方java程序?

1. 为第三方java程序生成.jar文件

2. 选择当前android项目→build path→config-build path→Libraries→Add External jars

优化Dalvik虚拟机的堆内存

//用此方法优化gc的效率,参考android源码TARGET_HEAP_UTILIZATION
// 活动的对象的内存/堆的大小
VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION)  //UTILIZATION = 0.75f
 
final static int HEAP_SIZE = 6* 1024* 1024 ;
VMRuntime.getRuntime().setMinimumHeapSize(HEAP_SIZE); //调整堆内存

使用tcpdump在android手机上进行抓包

使用tcpdump在android手机上进行抓包

运行tcpdump具有root权限

  1. 下载tcpdump文件tcpdump文件 tcpdump_001.zip
  2. adb push tcpdump /sdcard/tcpdump 安装文件
  3. adb shell tcpdump -p -vv -s 0 -w /sdcard/capture.pcap来进行抓包
  4. 使用 adb pull /sdcard/capture.pcap获取抓包数据
  5. 使用wireshark来查看抓包数据

使用系统生成的唯一id

在values/ids.xml中定义

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item type="id" name="button_ok" />
    <item type="id" name="dialog_exit" />
</resources>

使用时可以用showDialog(R.id.dialog_exit)

android修改Hosts文件

$su
#mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system
echo "168.143.161.20 twitter.com www.twitter.com" >> /etc/hosts
mount -o remount,ro -t yaffs2 /dev/block/mtdblock3 /system

在处理sqlite转义字符

SQLite转义字符

在 selection 中需要嵌入字符串的地方用 ? 代替,然后在 selectionArgs 中依次提供各个用于替换的值就可以了。在 query() 执行时会对 selectionArgs 中的字符串正确转义并替换到对应的 ? 处以构成完整的 selection 字符串。 有点像 String.format()。

public void doQuery(long id, final String name) {
  mDb.query("some_table", // table name
        null, // columns
        "id=" + id + " AND name=?", // selection
        new String[] {name}, //selectionArgs
         //...... 更多参数省略
  );
  // ...... 更多代码
}
}

如何查看padding和margin

如何向cursor写入数据

如何向一个cursor里添加额外的数据而又不改变数据库里的数据?

You can subclass SQLiteDatabase.CursorFactory to return, from its 
newCursor method, a subclass of SQLiteCursor. This factory gets passed 
to the SQLiteOpenHelper constructor so, when you query it, it will 
return Cursors of your new SQLiteCursor subclass type. 
The SQLiteCursor subclass can then expose methods that manage its 
protected mWindow field, which is a CursorWindow. This object has 
putXxx methods to manipulate the data. 
I haven't tried this myself, so if anyone has any tips or hints, 
please post. 

模拟器修改hosts文件

emulator -avd youravdname -partition-size 128
adb shell ping mm.maxthon.cn
adb root
adb remount
adb pull /system/etc/hosts /tmp/hosts
echo "192.168.1.32 mm.maxthon.cn" >> /tmp/hosts
adb push /tmp/hosts /system/etc/hosts
adb shell ping mm.maxthon.cn

如何获取指定类型的activity 列表 ?

有时候我们需要获取某一类activity的列表,如属性为 Intent.CATEGORY_LAUNCHER (可以启动的应用) 列表. 可以使用以下方法

 Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
 
        PackageManager pm = getPackageManager();
        List<ResolveInfo> list = pm.queryIntentActivities(mainIntent, 0);

发散思维: 我们可以自定义一类activity为我们的主activity服务.比如在插件系统中我们定义一个”com.mx.browser.plugin”的类别.

svn遇到is already under version control 解决办法?

解决办法:以uploads目录为例

删除uploads目录下的.svn目录及下面的文件(保留uploads目录的.svn) #find uploads |grep 'uploads/[^\.]*/.svn'|xargs rm -rf

当发生分支不能合并到主干时怎么办?

  1. 列出自己修改过的类
  2. 使用vimdiff工具,比较这些文件,合并很方便
  3. 检查合并过去的类

需要输入一个很长很长的网址时

  1. 在pc浏览器上输入 http://qrcode.kaywa.com/img.php?s=5&d=加上你的网址
  2. 上面的结果会生成一个二维码,使用手机的二维码识别程序,识别就好了

svn修改账户

删除 eclipse/configuration/org.eclipse.core.runtime/.keyring

点击Dialog外部令Dialog自动消失

设置Dialog.setCanceledOnTouchOutside(true);


第1章 搭建Android源码工作环境 1.1 Android系统架构 1.2 搭建开发环境 1.2.1 下载源码 1.2.2 编译源码 1.2.3 利用Eclipse调试system_process 1.3 本章小结 第2章 深入理解Java Binder和MessageQueue 2.1 概述 2.2 Java层中的Binder架构分析 2.2.1 Binder架构总览 2.2.2 初始化Java层Binder框架 2.2.3 addService实例分析 2.2.4 Java层Binder架构总结 2.3 心系两界的MessageQueue 2.3.1 MessageQueue的创建 2.3.2 提取消息 2.3.3 nativePollOnce函数分析 2.3.4 MessageQueue总结 2.4 本章小结 第3章 深入理解SystemServer 3.1 概述 3.2 SystemServer分析 3.2.1 main函数分析 3.2.2 Service群英会 3.3 EntropyService分析 3.4 DropBoxManagerService分析 3.4.1 DBMS构造函数分析 3.4.2 dropbox日志文件的添加 3.4.3 DBMS和settings数据库 3.5 DiskStatsService和DeviceStorageMonitorService分析 3.5.1 DiskStatsService分析 3.5.2 DeviceStorageManagerService分析 3.6 SamplingProfilerService分析 3.6.1 SamplingProfilerService构造函数分析 3.6.2 SamplingProfilerIntegration分析 3.7 ClipboardService分析 3.7.1 复制数据到剪贴板 3.7.2 从剪切板粘贴数据 3.7.3 CBS中的权限管理 3.8 本章小结 第4章 深入理解PackageManagerService 4.1 概述 4.2 初识PackageManagerService 4.3 PKMS的main函数分析 4.3.1 构造函数分析之前期准备工作 4.3.2 构造函数分析之扫描Package 4.3.3 构造函数分析之扫尾工作 4.3.4 PKMS构造函数总结 4.4 APK Installation分析 4.4.1 adb install分析 4.4.2 pm分析 4.4.3 installPackageWithVerification函数分析 4.4.4 APK 安装流程总结 4.4.5 Verification介绍 4.5 queryIntentActivities分析 4.5.1 IntentIntentFilter介绍 4.5.2 Activity信息的管理 4.5.3 Intent 匹配查询分析 4.5.4 queryIntentActivities总结 4.6 installd及UserManager介绍 4.6.1 installd介绍 4.6.2 UserManager介绍 4.7 本章学习指导 4.8 本章小结 第5章 深入理解PowerManagerService 5.1 概述 5.2 初识PowerManagerService 5.2.1 PMS构造函数分析 5.2.2 init分析 5.2.3 systemReady分析 5.2.4 BootComplete处理 5.2.5 初识PowerManagerService总结 5.3 PMS WakeLock分析 5.3.1 WakeLock客户端分析 5.3.2 PMS acquireWakeLock分析 5.3.3 Power类及LightService类介绍 5.3.4 WakeLock总结 5.4 userActivity及Power按键处理分析 5.4.1 userActivity分析 5.4.2 Power按键处理分析 5.5 BatteryService及BatteryStatsService分析 5.5.1 BatteryService分析 5.5.2 BatteryStatsService分析 5.5.3 BatteryService及BatteryStatsService总结 5.6 本章学习指导 5.7 本章小结 第6章 深入理解ActivityManagerService 6.1 概述 6.2 初识ActivityManagerService 6.2.1 ActivityManagerService的main函数分析 6.2.2 AMS的 setSystemProcess分析 6.2.3 AMS的 installSystemProviders函数分析 6.2.4 AMS的 systemReady分析 6.2.5 初识ActivityManagerService总结 6.3 startActivity分析 6.3.1 从am说起 6.3.2 AMS的startActivityAndWait函数分析 6.3.3 startActivityLocked分析 6.4 Broadcast和BroadcastReceiver分析 6.4.1 registerReceiver流程分析 6.4.2 sendBroadcast流程分析 6.4.3 BROADCAST_INTENT_MSG消息处理函数 6.4.4 应用进程处理广播分析 6.4.5 广播处理总结 6.5 startService之按图索骥 6.5.1 Service知识介绍 6.5.2 startService流程图 6.6 AMS中的进程管理 6.6.1 Linux进程管理介绍 6.6.2 关于Android中的进程管理的介绍 6.6.3 AMS进程管理函数分析 6.6.4 AMS进程管理总结 6.7 App的 Crash处理 6.7.1 应用进程的Crash处理 6.7.2 AMS的handleApplicationCrash分析 6.7.3 AppDeathRecipient binderDied分析 6.7.4 App的Crash处理总结 6.8 本章学习指导 6.9 本章小结 第7章 深入理解ContentProvider 7.1 概述 7.2 MediaProvider的启动及创建 7.2.1 Context的getContentResolver函数分析 7.2.2 MediaStore.Image.Media的query函数分析 7.2.3 MediaProvider的启动及创建总结 7.3 SQLite创建数据库分析 7.3.1 SQLite及SQLiteDatabase家族 7.3.2 MediaProvider创建数据库分析 7.3.3 SQLiteDatabase创建数据库的分析总结 7.4 Cursor 的query函数的实现分析 7.4.1 提取query关键点 7.4.2 MediaProvider 的query分析 7.4.3 query关键点分析 7.4.4 Cursor query实现分析总结 7.5 Cursor close函数实现分析 7.5.1 客户端close的分析 7.5.2 服务端close的分析 7.5.3 finalize函数分析 7.5.4 Cursor close函数总结 7.6 ContentResolver openAssetFileDescriptor函数分析 7.6.1 openAssetFileDescriptor之客户端调用分析 7.6.2 ContentProvider的 openTypedAssetFile函数分析 7.6.3 跨进程传递文件描述符的探讨 7.6.4 openAssetFileDescriptor函数分析总结 7.7 本章学习指导 7.8 本章小结 第8章 深入理解ContentService和AccountManagerService 8.1 概述 8.2 数据更新通知机制分析 8.2.1 初识ContentService 8.2.2 ContentResovler 的registerContentObserver分析 8.2.3 ContentResolver的 notifyChange分析 8.2.4 数据更新通知机制总结和深入探讨 8.3 AccountManagerService分析 8.3.1 初识AccountManagerService 8.3.2 AccountManager addAccount分析 8.3.3 AccountManagerService的分析总结 8.4 数据同步管理SyncManager分析 8.4.1 初识SyncManager 8.4.2 ContentResolver 的requestSync分析 8.4.3 数据同步管理SyncManager分析总结 8.5 本章学习指导 8.6 本章小结
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值