代码:
| 
					 1  | 
						android:launchMode=”singleTask”  | 
					
说明:对 manifest 文件中的相应 activity 属性增加该语句即可。
我可能前进得不快,但我决不后退
代码:
| 
					 1  | 
						android:launchMode=”singleTask”  | 
					
说明:对 manifest 文件中的相应 activity 属性增加该语句即可。
代码与范例:
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16  | 
						// 添加常驻通知 private void setNotification() {     NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);     Notification notification = new Notification(R.drawable.icon, getString(R.string.app_name), System.currentTimeMillis());     Intent intent = new Intent(this, Sample.class);     notification.flags = Notification.FLAG_ONGOING_EVENT; // 设置常驻 Flag     PendingIntent contextIntent = PendingIntent.getActivity(this, 0, intent, 0);     notification.setLatestEventInfo(getApplicationContext(), getString(R.string.app_name), getString(R.string.information), contextIntent);     notificationManager.notify(R.string.app_name, notification); } // 取消通知 private void cancelNotification() {     NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);     notificationManager.cancel(R.string.app_name); }  | 
					
说明:通过 setNotification() 可以在通知栏中添加一条常驻通知,通过 cancelNotification() 取消该通知。
代码与范例:
| 
					 1 2 3  | 
						tagfilter=tagfilter.replace("'", "''"); sel = "tag ='" + tagfilter + "'"; Cursor c = db.query(DB_TABLE, new String[] { "title", "tag", "deadline" }, sel, null, null, null, "id");  | 
					
说明:Android 所采用的 SQLite 数据库在 query,execSQL 等操作时无法识别字符串中出现的单引号(’),而会导致 SQLiteException。比如在范例中,若 tagfilter 的值为 Harry’s personal life ,则会出现错误,因为 s 之前的单引号会被识别为语句终结符。比较简单的解决方法就是通过 replace() 将原单引号替换为连续两个的单引号(”)。注意 replaceAll() 需要提供正则表达式,用法有所不同。
此外 SQLite 对于 ContentValues 方式或是 execSQL (String sql, Object[] bindArgs) 方法不会有这一问题,也可作为一种解决方案。
代码与范例:
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75  | 
						// 通过类 ProgressBarUpdater 来控制线程的运行状态 public class ProgressBarUpdater implements Runnable {     private volatile boolean paused = true;     private volatile boolean finished = false;     public void run() {         while (!finished) {             // wait             try {                 Thread.sleep(500);             } catch (InterruptedException e1) {             }             if (!paused) {             // Update the progress status             ProgressStatus = doWork();             progressBar.setProgress(ProgressStatus);             }                 while (paused && !finished) {                 // wait                 try {                     Thread.sleep(500);                 } catch (InterruptedException e) {                     }             }         }     }     public synchronized void pauseProgressBar() {         paused = true;     }     public synchronized void unPauseProgressBar() {         paused = false;         // call notify() here when you switch to wait/notify.     }     public void stopProgressBar() {         finished = true;         // call notify() here too.     } } @Override public void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.main);     setTitle(getResources().getString(R.string.number));     ProgressStatus = 0;     Button1 = (Button) this.findViewById(R.id.button1);     Button1.setOnClickListener(this);     Button2 = (Button) this.findViewById(R.id.button2);     Button2.setOnClickListener(this);     progressBar = (ProgressBar) findViewById(R.id.progressBar1);     progressBar.setMax(100);     progressBar.setProgress(0);     // progressBar.setSecondaryProgress(70);     // 使用 ProgressBarUpdater 来构造新的线程     ProgressBarUpdater pbu = new ProgressBarUpdater();     Thread t = new Thread(pbu);     t.start();     pbu.pauseProgressBar(); } // 通过 ProgressBarUpdater 来控制进度条的运行状态 @Override public void onClick(View v) {     if (v.getId() == R.id.button1) {         pbu.unPauseProgressBar();     }     if (v.getId() == R.id.button2) {         pbu.pauseProgressBar();     } }  | 
					
说明:可以通过一个辅助类来方便地改变控制 ProgressBar 的线程的运行状态。一个可以暂停与中断的进度条在有些情况下是很必要的。
代码与范例:
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21  | 
						// 创建并绑定 SeekBar SeekBar seekBar = (SeekBar) this.findViewById(R.id.seekBar1); // 设置 SeekBar 的最大值与初始位置 seekBar.setMax(10); seekBar.setProgress(3); seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {     @Override     public void onStartTrackingTouch(SeekBar seekBar) {     // 开始拖动 SeekBar 时的行为     }     @Override     public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {     // 正在拖动 SeekBar 时的行为。progress 为 SeekBar 当前所处位置     }     @Override     public void onStopTrackingTouch(SeekBar seekBar) {     // 停止拖动 SeekBar 时的行为             } });  | 
					
说明:SeekBar 是 Android UI 中常用的组件,在有范围的快速数值选择情况下能发挥较好的作用。
代码与范例:
| 
					 1 2 3 4 5 6 7 8 9 10  | 
						public boolean hasGPSDevice(Context context) {     final LocationManager mgr = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);     if ( mgr == null )          return false;     final List<String> providers = mgr.getAllProviders();     if ( providers == null )          return false;     return providers.contains(LocationManager.GPS_PROVIDER); }  | 
					
说明:通常Android设备有三种方式取得地理信息,GPS、移动网络和WiFi。GPS的表示名为”gps”,而移动网络和WiFi的表示名为”network”,它们统称为”provider”。因此,GPS_PROVIDER指的是GPS定位,而NETWORK_PROVIDER就是指后两种定位方式。
代码与范例:
| 
					 1 2 3 4 5 6 7 8  | 
						private static final float DIP = 16.0f; // 将dip转换为pixel,将pixel转换为dip只需将算式进行逆运算即可 final float scale = getContext().getResources().getDisplayMetrics().density; int pixel = (int) (DIP * scale + 0.5f); // 获取屏幕高度的像素值 getContext().getResources().getDisplayMetrics().heightPixels;  | 
					
说明:将像素值与Android的尺寸单位dp转换。dp/sp的意义基本相同,都是与屏幕密度无关的尺寸单位,只不过前者用于字体尺寸以外的场合,而后者用于指定字体尺寸。在不同情况下,dp和sp所表示的尺寸会有些不同,这部分内容将在之后补充。
启动浏览器
代码与范例:
| 
					 1 2  | 
						Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));   startActivity(intent);  | 
					
说明:启动浏览器并前往http://www.google.com 。
启动拨号程序
代码与范例:
| 
					 1 2  | 
						Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:138")); startActivity(intent);  | 
					
说明:启动拨号程序并输入号码138。
通话
代码与范例:
| 
					 1 2 3  | 
						Uri uri=Uri.parse("tel:138"); Intent intent=new Intent(Intent.ACTION_CALL,uri); startActivity(intent);  | 
					
说明:拨打号码138。需要为程序申请权限<uses-permission android:name=”android.permission.CALL_PHONE”/>。
发送短信
代码与范例:
| 
					 1 2 3 4  | 
						Uri smsUri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, smsUri); intent.setType("vnd.android-dir/mms-sms"); startActivity(intent);  | 
					
说明:启动短信程序。
启动通讯录
代码与范例:
| 
					 1 2  | 
						Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("content://contacts/people/1")); startActivity(intent);  | 
					
说明:启动同学录的某一条目。
启动地图程序(Google Maps等)
代码与范例:
| 
					 1 2 3  | 
						Uri mapUri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, mapUri); startActivity(intent);  | 
					
说明:启动地图程序。
搜索路线
代码与范例:
| 
					 1 2 3 4 5  | 
						Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setClassName("com.google.android.apps.maps","com.google.android.maps.MapsActivity"); intent.setData(Uri.parse("http://maps.google.com/maps?myl=saddr&daddr=&dirflg=d")); startActivity(intent);  | 
					
说明:启动Google Maps并搜索路线,具体的方法另外补充。
启动邮件程序
代码与范例:
| 
					 1 2 3 4 5  | 
						Uri uri =Uri.parse("mailto:xxx@example.com"); Intent intent = newIntent(Intent.ACTION_SENDTO, uri); intent.putExtra(Intent.EXTRA_SUBJECT, "Hello world"); intent.putExtra(Intent.EXTRA_TEXT, "Ganbarimasu"); startActivity(intent);  | 
					
说明:启动邮件程序并将收件人设为xxx@example.com,邮件主题设为Hello world,内容设为Ganbarimasu。
启动邮件程序并添加多个收件人
代码与范例:
| 
					 1 2 3 4 5 6 7 8 9  | 
						Intent intent=new Intent(Intent.ACTION_SEND);      String[] tos={"me@example.com"};      String[]ccs={"you@example.com"};      intent.putExtra(Intent.EXTRA_EMAIL, tos);      intent.putExtra(Intent.EXTRA_CC, ccs);      intent.putExtra(Intent.EXTRA_TEXT, "The email body text");      intent.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");      intent.setType("message/rfc822");      startActivity(Intent.createChooser(intent,"Choose Email Client"));  | 
					
说明:启动邮件程序并设置为发送给多个收件人。
启动邮件程序并添加附件
代码与范例:
| 
					 1 2 3 4 5  | 
						Intent intent = newIntent(Intent.ACTION_SEND);    intent.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");     intent.putExtra(Intent.EXTRA_STREAM,"file:///sdcard/mysong.mp3);    sendIntent.setType("audio/mp3");    startActivity(Intent.createChooser(intent,"Choose Email Client"));  | 
					
说明:启动邮件程序并添加附件。
播放MP3文件
代码与范例:
| 
					 1 2 3 4  | 
						Intent intent = new Intent(Intent.ACTION_VIEW); Uri uri =Uri.parse("file:///sdcard/song.mp3"); intent.setDataAndType(uri,"audio/mp3"); startActivity(intent);  | 
					
说明:启动音乐程序并播放MP3歌曲。
卸载程序
代码与范例:
| 
					 1 2 3  | 
						Uri uri =Uri.fromParts("package", strPackageName, null);    Intent intent = newIntent(Intent.ACTION_DELETE, uri);    startActivity(intent);  | 
					
说明:卸载包名为strPackageName的程序。
安装程序
代码与范例:
| 
					 1 2  | 
						Uri installUri = Uri.fromParts("package",strPackageName, null); returnIt = newIntent(Intent.ACTION_PACKAGE_ADDED, installUri);  | 
					
说明:安装包名为strPackageName的程序。
启动设置
代码与范例:
| 
					 1 2  | 
						Intent intent=new Intent("android.settings.SETTINGS"); startActivity(intent);  | 
					
说明:进入设定程序。
启动电子市场
代码与范例:
| 
					 1 2 3  | 
						Uri uri=Uri.parse("market://search?q=pname:org.breezesoft.techolite"); Intent intent=new Intent(Intent.ACTION_VIEW,uri); startActivity(intent);  | 
					
说明:以包名org.breezesoft.techolite为条件启动Android Market。
启动电子市场并进入程序信息界面
代码与范例:
| 
					 1 2 3  | 
						Uri uri = Uri.parse("market://details?id=org.breezesoft.techolite"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent);  | 
					
说明:启动Android Market并进入包名为org.breezesoft.techolite的程序的详细信息界面。
从图库(Gallery)中选择并获取一张图片
代码与范例:
| 
					 1 2 3 4  | 
						Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, 11);  | 
					
说明:启动图库并中选择并获取一张图片,返回原程序。
代码:Environment.getExternalStorageState();
范例:
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23  | 
						String status = Environment.getExternalStorageState(); if (status.equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {     Toast.makeText(TechoLite.this, "SD卡存在", Toast.LENGTH_LONG).show();     // 此时SD是可读写的 } else if (status.equalsIgnoreCase(Environment.MEDIA_MOUNTED_READ_ONLY)) {     Toast.makeText(TechoLite.this, "虽然SD存在,但是为只读状态", Toast.LENGTH_LONG).show(); } else if (status.equalsIgnoreCase(Environment.MEDIA_REMOVED)) {     Toast.makeText(TechoLite.this, "SD不存在", Toast.LENGTH_LONG).show(); } else if (status.equalsIgnoreCase(Environment.MEDIA_SHARED)) {     Toast.makeText(TechoLite.this, "虽然SD卡存在,但是正与PC等相连接", Toast.LENGTH_LONG).show(); } else if (status.equalsIgnoreCase(Environment.MEDIA_BAD_REMOVAL)) {     Toast.makeText(TechoLite.this, "SD卡在挂载状态下被错误取出", Toast.LENGTH_LONG).show(); } else if (status.equalsIgnoreCase(Environment.MEDIA_CHECKING)) {     Toast.makeText(TechoLite.this, "正在检查SD卡", Toast.LENGTH_LONG).show(); } else if (status.equalsIgnoreCase(Environment.MEDIA_NOFS)) {     Toast.makeText(TechoLite.this, "虽然SD卡存在,但其文件系统不被支持", Toast.LENGTH_LONG).show(); } else if (status.equalsIgnoreCase(Environment.MEDIA_UNMOUNTABLE)) {     Toast.makeText(TechoLite.this, "虽然SD卡存在,但是无法被挂载", Toast.LENGTH_LONG).show(); } else if (status.equalsIgnoreCase(Environment.MEDIA_UNMOUNTED)) {     Toast.makeText(TechoLite.this, "虽然SD卡存在,但是未被挂载", Toast.LENGTH_LONG).show(); } else {     Toast.makeText(TechoLite.this, "其他原因", Toast.LENGTH_LONG).show(); }  | 
					
说明:用于判断设备的SD卡的状态。
代码与范例:
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22  | 
						@Override public boolean onCreateOptionsMenu(Menu menu) {     super.onCreateOptionsMenu(menu);     return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) {     super.onCreateOptionsMenu(menu);     // 清除菜单内容后由条件判断语句决定如何生成选项菜单     menu.clear();     if (condition == 0) {         MenuItem item0 = menu.add(0, 0, 0, R.string.text1a);         item0.setIcon(android.R.drawable.icon1a);     } else {         MenuItem item0 = menu.add(0, 0, 0, R.string.text1b);         item0.setIcon(android.R.drawable.icon1b);     }     MenuItem item1 = menu.add(0, 1, 0, R.string.text2);     item1.setIcon(android.R.drawable.icon2);     return true; }  | 
					
说明:有的时候需要选项菜单(Options Menu)的内容根据情况调整,这时只要覆写onPrepareOptionsMenu方法即可。注意不要忘记清除菜单中的原有内容。