现在的位置: 首页 > 综合 > 正文

android 技巧

2018年06月09日 ⁄ 综合 ⁄ 共 36795字 ⁄ 字号 评论关闭

技巧篇

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

遇到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);

抱歉!评论已关闭.