Android 学习笔记
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属性,主题,加入下面的项
<item name="android:windowNoTitle">true</item>
设置背景半暗
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设置,以防以后忘记了,,,
<item name="android:windowBackground">@drawable/color_translucent</item>
<item name="android:windowIsTranslucent">true</item>
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<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
20.
手机振动,代码片段。
Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(pattern, -1);
需要在AndroidManifest.xml文件添加权限
<uses-permission android:name="android.permission.VIBRATE" />
21.
设置开机运行程序,需要在AndroidManifest.xml中添加
<intent-filter>
<!-- 系统启动完成后会调用-->
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
22.
简单的使用ListView的方法,
一,单行文字的
List<String> list = new ArrayList<String>();
lvData.setAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, list));
二,双行文字,使用SimpleAdapter
List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
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 隐藏应用程序图标
把<category android:name="android.intent.category.LAUNCHER" />删除即可
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<Thread, StackTraceElement[]> 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
<uses-configuration android:reqTouchScreen="finger" />
34.
设置某activity只能有一个实例
<activity android:name=".TTSActivity"
android:label="@string/app_name"
android:launchMode="singleTask">
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" > /sys/devices/virtual/bdi/179\:0/read_ahead_kb
37.
java获取当前时间的字符串
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
String str = format.format(new java.util.Date());