《尚学堂Android笔记大全.doc》由会员分享,可在线阅读,更多相关《尚学堂Android笔记大全.doc(33页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、Android 学习笔记1.长点击控件菜单,即我们常说的右键菜单,不过好像ContextMenu不支持ICON的,所以即使在源码里面可以使用setIcon函数,但是还是不会有效果的。一般有下面三个步骤:/ 通常在onCreate函数中注册一个控件,btn为需要弹出ContextMenu的控件this.registerForContextMenu(btn);/ 下面函数是创建ContextMenu的,v是被点击的控件/ 根据v进行判断可以对不同的控件,创建不同的ContextMenupublic void onCreateContextMenu(ContextMenu menu, View v,
2、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 abst
3、ract 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.获取屏幕的分辨率DisplayM
4、etrics dm = new DisplayMetrics();getWindowManager().getDefaultDisplay().getMetrics(dm);dm.widthPixelsdm.heightPixels5.显示POPUP对话框,类似于Windows的MessageBox函数,不过这个要比MessageBox强大多了,可以设置单选或者多选项,以及其响应,有两种方法可以一:实现Activity的onCreateDialog函数。showDialog(ID_TEST_DIALOG);protected Dialog onCreateDialog(int id) / TO
5、DO Auto-generated method stubswitch (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 A
6、uto-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
7、 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)
8、;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;
9、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.当按返回键时,完全按退出系统Overrideprotected void onDestroy() / TODO Auto-generated method stubandroid.os.Process.killProcess(android.os.Pr
10、ocess.myPid();super.onDestroy();Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) / TODO Auto-generated method stubif (keyCode = KeyEvent.KEYCODE_BACK) finish();return true;return super.onKeyDown(keyCode, event);9.获取状态栏和标题栏的高度获取状态栏高度: decorView是window中的最顶层view,可以从window中获取到decorView,然后de
11、corView有个getWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。 于是,我们就可以算出状态栏的高度了。Rect frame = new Rect(); getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top; 获取标题栏高度: getWindow().findViewById(Window.ID_ANDROID_CONTENT)这个方法获取到的view就是程序不包括标题栏的部分,然后就可以知道
12、标题栏的高度了。 int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); /statusBarHeight是上面所求的状态栏的高度 int titleBarHeight = contentTop - statusBarHeight 10.关于窗口的一些操作不显示标题栏getWindow().requestFeature(Window.FEATURE_NO_TITLE);或者是设置一个style属性,主题,加入下面的项true设置背景半暗LayoutParams lp = getWindow()
13、.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设置,以防以后
14、忘记了,drawable/color_translucenttrue11.获取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 block
15、Size = 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.getRootDirector
16、y(); 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系统中定义了很多动画与样式,
17、我们可能在eclipse开发程序的时候使用系统定义的资源,哈哈,这样可以保持与系统显示的样式一致对于定义为:android.R.drawable.status_bar_item_background的样式,只需在eclipse的资源文件中写为:android:drawable/status_bar_item_background总结一下,所以可以写为下面的样子。android:background=android:drawable/status_bar_item_background13.Android.mk文件的说明。JAR: include $(BUILD_JAVA_LIBRARY),源文
18、件为javaSO:include $(BUILD_SHARED_LIBRARY),源文件为 c或cAPK: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 sendVKeyDel
19、ay(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
20、(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应该注意的异常,处理各种情况跟异
21、常! 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_n
22、ot_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 = nul
23、l) 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
24、_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(ne
25、w 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).inf
26、late(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.gr
27、avity = 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
28、 = getPackageManager();final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);final List apps = packageManager.queryIntentActivities(mainIntent, 0);20.手机振动,代码片段。Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);vibrator.
29、vibrate(pattern, -1);需要在AndroidManifest.xml文件添加权限21.设置开机运行程序,需要在AndroidManifest.xml中添加22.简单的使用ListView的方法,一,单行文字的List list = new ArrayList();lvData.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);二,双行文字,使用SimpleAdapterListHashMap list = new ArrayListHashMap();HashMap map
30、 = new HashMap();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 StringID,UserName,new intandroid.R.id.text1, android.R.id.text2);23.SQLiteDatabase中模拟使用Truncate方法清空
31、数据表跟计数器的方法先使用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.LENG
32、TH_LONG).show();se.printStackTrace();24.使用ADB以可读写方式重新挂载根目录,可以读写sbin文件夹./adb shellsumount -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 = runtim
33、e.exec(command); catch (IOException e) Log.i(zyl,chmod fail!);e.printStackTrace();26.Android 隐藏应用程序图标把删除即可27.使用Tab分页内容。 public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); TabHost mTabHost = this.getTabHost(); Intent intent = new Intent(this, TabContent.class); intent
34、.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(
35、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的时候添加
36、窗口标志: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 mMedia
37、Player.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.setLoopi
38、ng(false);mMediaPlayer.prepare();mMediaPlayer.start(); catch (IllegalArgumentException e) / TODO Auto-generated catch blocke.printStackTrace(); catch (SecurityException e) / TODO Auto-generated catch blocke.printStackTrace(); catch (IllegalStateException e) / TODO Auto-generated catch blocke.printSt
39、ackTrace(); catch (IOException e) / TODO Auto-generated catch blocke.printStackTrace();30.打印当前函数的系统调用堆栈java.util.Map ts = Thread.getAllStackTraces();StackTraceElement ste = ts.get(Thread.currentThread();for (StackTraceElement s : ste) Log.i(TAG, StackTraceElement :+s.toString();31.获取当前函数的函数名称Thread.
40、currentThread().getStackTrace()2.getMethodName();32.往手机发送一个按键消息,event号可能按手机而不一样,第一个1是表示按键事件,139是键值,后面的数值1表示down,0表示upadb shell sendevent /dev/input/event1 1 139 1 & adb shell sendevent /dev/input/event1 1 139 033.指定使用finger layout,AndroidManifest.xml34.设置某activity只能有一个实例35.使用adb shell启动一个activity. -
41、n 后面跟着的是包名/.需要启动的类名adb shell am start -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -n com.android.contacts/.DialtactsContactsEntryActivity -f 0x1020000036.增大SD卡的读写缓存,以KB为单位,下面设置2048KBecho 2048 /sys/devices/virtual/bdi/179:0/read_ahead_kb37.java获取当前时间的字符串SimpleDateFormat format =
42、 new SimpleDateFormat(yyyyMMddhhmmss);String str = format.format(new java.util.Date();有时候,需要一些小的功能,找到以后,就把它贴到了博客下面,作为留言,查找起来很不方便,所以就整理一下,方便自己和他人。一、 获取系统版本号:javaview plaincopyPackageInfo info = this.getPackageManager().getPackageInfo(this.getPackageName(), 0); int versionCode=nfo.versionCode string versionName=info.versionNam 二、获取系统信息:javaview plaincopyString archiv