---
title: "Android 学习笔记"
author: "badboywang"
date: "2012-03-13T10:56:16Z"
tags: []
categories: ["移动开发"]
slug: "android"
draft: false
lastmod: "2012-03-13T10:56:16Z"
id: 1452084
url: "https://badboywang.iteye.com/blog/1452084"
---

1\.

长点击控件菜单,即我们常说的右键菜单，不过好像ContextMenu不支持ICON的，  
所以即使在源码里面可以使用setIcon函数，但是还是不会有效果的。。。  
一般有下面三个步骤：  
// 通常在onCreate函数中注册一个控件，btn为需要弹出ContextMenu的控件

this.registerForContextMenu(btn);  
///////////////////////////////////////////////////////////////////////////////  
// 下面函数是创建ContextMenu的，v是被点击的控件  
// 根据v进行判断可以对不同的控件，创建不同的ContextMenu  
public void onCreateContextMenu(ContextMenu menu, View v,  
ContextMenuInfo menuInfo)  
///////////////////////////////////////////////////////////////////////////////  
// 下面函数是响应ContextMenu点击事情的。。  
public boolean onContextItemSelected(MenuItem item)

2\.  
Toast显示信息，可以方便的来输出信息  
Toast.makeText(this, "Info", Toast.LENGTH\_LONG).show();

3\.  
关于MENU的操作  
有两个比较重要的了，函数原型：  
public abstract MenuItem add (int groupId, int itemId, int order, CharSequence title);  
public abstract SubMenu addSubMenu (CharSequence title);  
一般的函数有：  
menu.setHeaderTitle("MenuTitle");  
menu.setHeaderIcon(R.drawable.icon);  
menu.add(0, 0, 0, "item0").setIcon(R.drawable.icon);  
menu.add(0, 1, 1, "item1");  
///////////////////////////////////////////////////////////////////////////////  
SubMenu sub = menu.addSubMenu("SubMenu");  
sub.add(0, 5, 5, "item5");  
sub.add(0, 6, 6, "item6");

 

 

4\.  
获取屏幕的分辨率  
isplayMetrics dm = new DisplayMetrics();  
getWindowManager().getDefaultDisplay().getMetrics(dm);  
dm.widthPixels  
dm.heightPixels

5\.  
显示POPUP对话框，类似于Windows的MessageBox函数，不过这个要比MessageBox强大多了，，，  
可以设置单选或者多选项，以及其响应，有两种方法可以  
一：  
实现Activity的onCreateDialog函数。  
showDialog(ID\_TEST\_DIALOG);  
protected Dialog onCreateDialog(int id) {  
// TODO Auto-generated method stub  
switch (id) {  
case ID\_TEST\_DIALOG:  
Dialog dialog = new AlertDialog.Builder(this)  
.setTitle("AlertDialog Test")  
.setMessage("This is a test for AlertDialg!")  
.setPositiveButton("OK", new DialogInterface.OnClickListener() {  
public void onClick(DialogInterface dialog, int which) {  
// TODO Auto-generated method stub

}  
})  
.create();  
return dialog;  
default:  
break;  
}  
return super.onCreateDialog(id);  
}  
这里有个配套的函数  
dismissDialog(D\_TEST\_DIALOG);  
这个可以关闭相应的Dialog.  
///////////////////////////////////////////////////////////////////////////////  
二：  
直接调用Builder函数去完成创建与显示。  
new AlertDialog.Builder(this)  
.setTitle("AlertDialog Test")  
.setMessage("This is a test for AlertDialg!")  
.setPositiveButton("OK", new DialogInterface.OnClickListener() {  
public void onClick(DialogInterface dialog, int which) {  
// TODO Auto-generated method stub

}  
})  
.show();

6\.  
从一个xml布局获取其View的方法。  
这个好像有两种方法，不过都是得到一个LayoutInflater之后再inflate得到指定xml布局相对应的View.  
一：  
LayoutInflater li;  
li = (LayoutInflater)this.getSystemService(LAYOUT\_INFLATER\_SERVICE);  
View v = li.inflate(R.layout.la\_test, null);  
二：  
LayoutInflater li;  
li = LayoutInflater.from(this);  
View v = li.inflate(R.layout.la\_test, null);

7\.  
知道第二个方法和第六个方法之后，我们可以把这两个方法综合起来。  
就是可以自定义的显示一段时间的图形，这个说法有点抽象，简单一点就是做一个类似音量调节那样的浮动窗口。  
思路是这样的，可以新建一个Toast，然后再inflate一个布局，设置里面的内容，然后再把内容放到Toast里面显示  
LayoutInflater li;  
li = LayoutInflater.from(this);  
View v = li.inflate(R.layout.la\_test, null);  
Toast toast = new Toast(this);  
toast.setDuration(Toast.LENGTH\_LONG);  
toast.setView(v);  
toast.show();

8\.  
当按返回键时，完全按退出系统  
@Override  
protected void onDestroy() {  
// TODO Auto-generated method stub  
android.os.Process.killProcess(android.os.Process.myPid());  
super.onDestroy();  
}  
@Override  
public boolean onKeyDown(int keyCode, KeyEvent event) {  
// TODO Auto-generated method stub  
if (keyCode == KeyEvent.KEYCODE\_BACK) {  
finish();  
return true;  
}  
return super.onKeyDown(keyCode, event);  
}

9\.  
获取状态栏和标题栏的高度  
获取状态栏高度：   
decorView是window中的最顶层view，可以从window中获取到decorView，然后decorView有个getWindowVisibleDisplayFrame方法可以获取到程序显示的区域，包括标题栏，但不包括状态栏。   
于是，我们就可以算出状态栏的高度了。  
Rect frame = new Rect();    
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);    
int statusBarHeight = frame.top;   
获取标题栏高度：   
getWindow().findViewById(Window.ID\_ANDROID\_CONTENT)这个方法获取到的view就是程序不包括标题栏的部分，然后就可以知道标题栏的高度了。   
int contentTop = getWindow().findViewById(Window.ID\_ANDROID\_CONTENT).getTop();    
//statusBarHeight是上面所求的状态栏的高度    
int titleBarHeight = contentTop - statusBarHeight  

10\.  
关于窗口的一些操作  
不显示标题栏  
getWindow().requestFeature(Window.FEATURE\_NO\_TITLE);  
或者是设置一个style属性，主题，加入下面的项  
&lt;item name="android:windowNoTitle"&gt;true&lt;/item&gt;

设置背景半暗  
LayoutParams lp = getWindow().getAttributes();  
lp.dimAmount = 0.5f;  
// 设置透明度是alpha的值  
// lp.alpha = 0.8f;  
getWindow().setAttributes(lp);  
getWindow().addFlags(WindowManager.LayoutParams.FLAG\_DIM\_BEHIND);

设置背景模糊  
getWindow().setFlags(WindowManager.LayoutParams.FLAG\_BLUR\_BEHIND,  
WindowManager.LayoutParams.FLAG\_BLUR\_BEHIND);

一般可能有用的style设置，以防以后忘记了，，，  
&lt;item name="android:windowBackground"&gt;@drawable/color\_translucent&lt;/item&gt;  
&lt;item name="android:windowIsTranslucent"&gt;true&lt;/item&gt;

11\.  
获取SD卡总空间和可用空间  
public static String getSDcardStorage() {  
String state = Environment.getExternalStorageState();  
if(Environment.MEDIA\_MOUNTED.equals(state)) {  
File sdcardDir = Environment.getExternalStorageDirectory();  
   StatFs sf = new StatFs(sdcardDir.getPath());  
   long blockSize = sf.getBlockSize();  
   long blockCount = sf.getBlockCount();  
   long availCount = sf.getAvailableBlocks();  
   return "SD卡：" + formatSize(blockSize\*blockCount)  
    + " 可用空间：" + formatSize(availCount\*blockCount);  
}  
return null;  
}

获取系统空间和可用空间  
public static String getSystemStorage() {  
File root = Environment.getRootDirectory();     
        StatFs sf = new  StatFs(root.getPath());     
        long  blockSize = sf.getBlockSize();     
        long  blockCount = sf.getBlockCount();     
        long  availCount = sf.getAvailableBlocks();     
        return "总空间：" + formatSize(blockSize\*blockCount)  
     + " 可用空间：" + formatSize(availCount\*blockSize);  
    } 

 

 

12\.  
在资源文件中使用Android定义的资源的方法  
在Android系统中定义了很多动画与样式，我们可能在eclipse开发程序的时候使用系统定义的资源，  
哈哈，这样可以保持与系统显示的样式一致~~~  
对于定义为：android.R.drawable.status\_bar\_item\_background的样式，  
只需在eclipse的资源文件中写为：@android:drawable/status\_bar\_item\_background  
总结一下，所以可以写为下面的样子。。。  
android:background="@android:drawable/status\_bar\_item\_background"

13\.  
Android.mk文件的说明。  
JAR: include $(BUILD\_JAVA\_LIBRARY)，源文件为java  
SO:include $(BUILD\_SHARED\_LIBRARY)，源文件为 c或c＋＋  
APK:include $(BUILD\_PACKAGE)，源文件为java  
二进制可执行文件：include $(BUILD\_EXECUTABLE)，源文件为c或c＋＋

如需要在java文件中调用so文件，如：libabc.so则需在Android.mk文件中添加：  
LOCAL\_JNI\_SHARED\_LIBRARIES := libabc  
同时，需要在java文件中System.loadLibrary("abc");，注意此时不需要在加上lib前缀

14\.  
模拟按键消息  
private void sendVKeyDelay(int key) {  
final int keyCode = key;  
Thread sendKeyDelay = new Thread(){  
public void run() {  
try {  
Thread.sleep(100);

long now = SystemClock.uptimeMillis();  
KeyEvent keyDown = new KeyEvent(now, now, KeyEvent.ACTION\_DOWN,  
keyCode, 0);  
IWindowManager wm = IWindowManager.Stub.asInterface(  
ServiceManager.getService("window"));  
wm.injectKeyEvent(keyDown, false);

KeyEvent keyUp = new KeyEvent(now, now, KeyEvent.ACTION\_UP,  
keyCode, 0);  
wm.injectKeyEvent(keyUp, false);  
} catch (InterruptedException e) {  
e.printStackTrace();  
} catch (RemoteException e) {  
e.printStackTrace();  
}  
}  
};  
sendKeyDelay.start();  
}

15\.  
使用startActivity应该注意的异常，处理各种情况跟异常！！！  
    void startActivitySafely(Intent intent) {  
        intent.addFlags(Intent.FLAG\_ACTIVITY\_NEW\_TASK);  
        try {  
            startActivity(intent);  
        } catch (ActivityNotFoundException e) {  
            Toast.makeText(this, R.string.activity\_not\_found, Toast.LENGTH\_SHORT).show();  
        } catch (SecurityException e) {  
            Toast.makeText(this, R.string.activity\_not\_found, Toast.LENGTH\_SHORT).show();  
            e(LOG\_TAG, "Launcher does not have the permission to launch " + intent +  
                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +  
                    "or use the exported attribute for this activity.", e);  
        }  
    }

16\.  
创建动画效果。  
public void createAnimation() {  
if (mInAnimation == null) {  
mInAnimation  = new AnimationSet(false);  
final AnimationSet ani = mInAnimation;  
ani.setInterpolator(new AnticipateOvershootInterpolator(2.5f));  
ani.addAnimation(new AlphaAnimation(0.0f, 1.0f));  
ani.addAnimation(new TranslateAnimation(Animation.ABSOLUTE, 0.0f,   
Animation.ABSOLUTE, 0.0f, Animation.RELATIVE\_TO\_SELF, -1.0f,  
Animation.RELATIVE\_TO\_SELF, 0.0f));  
ani.setDuration(1000);  
}  
if (mOutAnimation == null) {  
mOutAnimation = new AnimationSet(false);  
AnimationSet ano = mOutAnimation;  
ano.setInterpolator(new AnticipateOvershootInterpolator(2.5f));  
ano.addAnimation(new AlphaAnimation(1.0f, 0.0f));  
ano.addAnimation(new TranslateAnimation(Animation.ABSOLUTE, 0.0f,   
Animation.ABSOLUTE, 0.0f, Animation.RELATIVE\_TO\_SELF, 0.0f,  
Animation.RELATIVE\_TO\_SELF, -1.0f));  
ano.setDuration(1000);  
}  
}

17\.  
显示一个浮动的窗口(任意View).  
mWindowManager = (WindowManager)getSystemService(  
Context.WINDOW\_SERVICE);  
mDialog = LayoutInflater.from(mContext).inflate(  
R.layout.popup, null);  
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(  
LayoutParams.WRAP\_CONTENT, LayoutParams.WRAP\_CONTENT,  
(int)event.getX(), (int)event.getY(),  
WindowManager.LayoutParams.TYPE\_APPLICATION,  
WindowManager.LayoutParams.FLAG\_NOT\_FOCUSABLE,  
PixelFormat.TRANSLUCENT);  
lp.gravity = Gravity.TOP | Gravity.LEFT;  
mWindowManager.addView(mDialog, lp);  
如果需要隐藏，则remove即可  
mWindowManager.removeView(mDialog);

18\.  
设置应用程序全屏显示  
this.requestWindowFeature(Window.FEATURE\_NO\_TITLE);  
getWindow().addFlags(WindowManager.LayoutParams.FLAG\_FULLSCREEN);

19\.  
获取系统所有的安装程序  
final PackageManager packageManager = getPackageManager();  
final Intent mainIntent = new Intent(Intent.ACTION\_MAIN, null);  
mainIntent.addCategory(Intent.CATEGORY\_LAUNCHER);  
final List&lt;ResolveInfo&gt; apps = packageManager.queryIntentActivities(mainIntent, 0);

20\.  
手机振动，代码片段。  
Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR\_SERVICE);  
vibrator.vibrate(pattern, -1);  
需要在AndroidManifest.xml文件添加权限  
&lt;uses-permission android:name="android.permission.VIBRATE" /&gt;

21\.  
设置开机运行程序，需要在AndroidManifest.xml中添加  
&lt;intent-filter&gt;  
&lt;!-- 系统启动完成后会调用--&gt;  
&lt;action android:name="android.intent.action.BOOT\_COMPLETED" /&gt;  
&lt;/intent-filter&gt;

22\.  
简单的使用ListView的方法，  
一，单行文字的  
List&lt;String&gt; list = new ArrayList&lt;String&gt;();  
lvData.setAdapter(new ArrayAdapter(this,   
android.R.layout.simple\_list\_item\_1, list));  
二，双行文字，使用SimpleAdapter  
List&lt;HashMap&lt;String, String&gt;&gt; list = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();  
HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();  
map.put("ID", cursor.getString(0));  
map.put("UserName", cursor.getString(1));  
list.add(map);  
lvData.setAdapter(new SimpleAdapter(this, list,   
android.R.layout.simple\_expandable\_list\_item\_2,   
new String\[]{"ID","UserName"},  
new int\[]{android.R.id.text1, android.R.id.text2}));

23\.  
SQLiteDatabase中模拟使用Truncate方法清空数据表跟计数器的方法  
先使用"DELETE FROM TableName"语句清空数据表数据  
再使用"UPDATE SQLITE\_SEQUENCE SET SEQ=0 WHERE NAME=\\"TableName\\""置0计数器  
下面是清空表“Users”  
try {  
mDatabase.execSQL("DELETE FROM Users");  
mDatabase.execSQL("update sqlite\_sequence set seq=0 where name=\\"Users\\"");  
} catch (SQLException se) {  
Toast.makeText(this, se.getMessage(), Toast.LENGTH\_LONG).show();  
se.printStackTrace();  
}

24\.  
使用ADB以可读写方式重新挂载根目录,可以读写sbin文件夹  
./adb shell  
su  
mount -o remount,rw dev/block/mtdblock3 /

25\.  
android中通过代码实现文件权限修改  
try {  
String command = "chmod 777 " + destFile.getAbsolutePath();  
Log.i("zyl", "command = " + command);  
Runtime runtime = Runtime.getRuntime();   
Process proc = runtime.exec(command);  
} catch (IOException e) {  
Log.i("zyl","chmod fail!!!!");  
e.printStackTrace();  
}

26\.  
Android 隐藏应用程序图标  
把&lt;category android:name="android.intent.category.LAUNCHER" /&gt;删除即可

27\.  
使用Tab分页内容。  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
          
        TabHost mTabHost = this.getTabHost();  
          
        Intent intent = new Intent(this, TabContent.class);  
        intent.setAction(Intent.ACTION\_VIEW);  
        intent.putExtra("Yao.GUET", 0);  
        mTabHost.addTab(mTabHost.newTabSpec("Tab\_1")  
         .setIndicator("Tab 1",   
         getResources().getDrawable(R.drawable.icon))  
         .setContent(intent));  
          
        Intent intent2 = new Intent(this, TabContent.class);  
        intent2.setAction(Intent.ACTION\_VIEW);  
        intent2.putExtra("Yao.GUET", 1);  
        mTabHost.addTab(mTabHost.newTabSpec("Tab\_2")  
         .setIndicator("Tab 2",   
         getResources().getDrawable(R.drawable.icon))  
         .setContent(intent2));  
          
        mTabHost.setCurrentTab(0);  
    }

28\.  
设置透明背景，修改AndroidManifest.xml文件，在对应的Activity里面加上下面的属性：  
android:theme="@android:style/Theme.Translucent"  
使用系统背景作为应用的背景，在onCreate的时候添加窗口标志：  
getWindow().addFlags(WindowManager.LayoutParams.FLAG\_SHOW\_WALLPAPER);

 

29\.  
播放系统铃声代码  
// play the notification sound...  
private void playNotifySound(Context context) {  
Uri Notify\_Sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE\_NOTIFICATION);   
MediaPlayer mMediaPlayer = new MediaPlayer();  
try {  
mMediaPlayer.setDataSource(context, Notify\_Sound);  
final AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO\_SERVICE);  
if (audioManager.getStreamVolume(AudioManager.STREAM\_NOTIFICATION) != 0) {  
mMediaPlayer.setAudioStreamType(AudioManager.STREAM\_NOTIFICATION);  
mMediaPlayer.setLooping(false);  
mMediaPlayer.prepare();  
mMediaPlayer.start();  
}  
} catch (IllegalArgumentException e) {  
// TODO Auto-generated catch block  
e.printStackTrace();  
} catch (SecurityException e) {  
// TODO Auto-generated catch block  
e.printStackTrace();  
} catch (IllegalStateException e) {  
// TODO Auto-generated catch block  
e.printStackTrace();  
} catch (IOException e) {  
// TODO Auto-generated catch block  
e.printStackTrace();  
}  
}

 

30\.

打印当前函数的系统调用堆栈

java.util.Map&lt;Thread, StackTraceElement\[]&gt; ts = Thread.getAllStackTraces();    
StackTraceElement\[] ste = ts.get(Thread.currentThread());    
for (StackTraceElement s : ste) {    
    Log.i(TAG, "StackTraceElement  :"+s.toString());   
}

 

31\.

获取当前函数的函数名称

Thread.currentThread().getStackTrace()\[2].getMethodName();

 

32\.

往手机发送一个按键消息，event号可能按手机而不一样，第一个1是表示按键事件，139是键值，后面的数值1表示down,0表示up

adb shell sendevent /dev/input/event1 1 139 1 && adb shell sendevent /dev/input/event1 1 139 0

 

33\.

指定使用finger layout，AndroidManifest.xml  
&lt;uses-configuration android:reqTouchScreen="finger" /&gt;

 

34\.

设置某activity只能有一个实例

&lt;activity android:name=".TTSActivity"  
                  android:label="@string/app\_name"  
                  android:launchMode="singleTask"&gt;

 

35\.

使用adb shell启动一个activity. -n 后面跟着的是包名/.需要启动的类名

adb shell am start -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -n com.android.contacts/.DialtactsContactsEntryActivity -f 0x10200000

 

36\.  
增大SD卡的读写缓存，以KB为单位，下面设置2048KB  
echo "2048" &gt; /sys/devices/virtual/bdi/179\\:0/read\_ahead\_kb

 

37\.

java获取当前时间的字符串

SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");  
String str =  format.format(new java.util.Date());