標籤:
在前台啟動並執行 Activity 可以通過Dialog、Toast 向使用者發出提示資訊,而後台啟動並執行程式,如下載、收到資訊等 Service 應用,則需要使用 Notification(通知)向使用者發出提示資訊。
1 import android.app.Activity; 2 import android.app.Notification; 3 import android.app.NotificationManager; 4 import android.app.PendingIntent; 5 import android.content.Context; 6 import android.content.Intent; 7 import android.os.Bundle; 8 import android.view.View; 9 import android.view.View.OnClickListener;10 import android.widget.Button;11 import android.widget.RemoteViews;12 13 public class NotificationActivity extends Activity {14 15 Button b1;16 NotificationManager nmanager;17 Notification notification;18 int notificationID=1;19 20 @Override21 protected void onCreate(Bundle savedInstanceState) {22 super.onCreate(savedInstanceState);23 24 setContentView(R.layout.notificationlayout);25 b1=(Button) findViewById(R.id.notification_bt1);26 b1.setOnClickListener(new OnClickListener(){27 @Override28 public void onClick(View v) {29 //sendNotification();30 sendCustomNotification();31 }}32 );33 }34 35 // 發送自訂通知36 public void sendCustomNotification(){37 //1.獲得 NotificationManager38 nmanager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);39 //2.建立 Notification40 notification =new Notification(41 R.drawable.folder_open,42 "收到檔案",43 System.currentTimeMillis()44 );45 RemoteViews rv = new RemoteViews(getPackageName(),R.layout.notificationinterfacelayout);46 rv.setImageViewResource(R.id.notification_img, R.drawable.savefile);47 rv.setTextViewText(R.id.notification_title, "催眠曲.mp3");48 rv.setProgressBar(R.id.notification_progressbar, 100, 20, false);49 notification.contentView=rv;50 //3.設定屬性,這些屬性會在展開狀態列後顯示51 Intent intent =new Intent(this,ToastActivity.class); //轉向其他52 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK); 53 PendingIntent pIntent=PendingIntent.getActivity(this, 0, intent, 0);54 notification.contentIntent=pIntent;55 //4.將Notification發給Manager56 nmanager.notify(notificationID++, notification);57 }58 59 // 發送通知60 public void sendNotification(){61 //1.獲得NotificationManager62 nmanager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);63 //2.建立Notification64 notification =new Notification(65 R.drawable.folder_open,66 "收到檔案",67 System.currentTimeMillis()68 );69 // 可選屬性70 notification.defaults|=Notification.DEFAULT_SOUND;71 notification.flags |=Notification.FLAG_INSISTENT;72 73 74 // 3.設定屬性,這些屬性會在展開狀態列後顯示75 Intent intent =new Intent(this,ToastActivity.class); //轉向其他76 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK); 77 PendingIntent pIntent=PendingIntent.getActivity(this, 0, intent, 0);78 notification.setLatestEventInfo(this, "接收檔案", "檔案已經下載完成", pIntent);79 // 4.將 Notification 發給 Manager80 nmanager.notify(notificationID++, notification);81 }82 83 }
Android 開發工具類 16_NotificationActivity