在前台运行的 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 @Override 21 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 @Override 28 public void onClick(View v) { 29 //sendNotification(); 30 sendCustomNotification(); 31 }} 32 ); 33 } 34 35 // 发送自定义通知 36 public void sendCustomNotification(){ 37 //1.获得 NotificationManager 38 nmanager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 39 //2.创建 Notification 40 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发给Manager 56 nmanager.notify(notificationID++, notification); 57 } 58 59 // 发送通知 60 public void sendNotification(){ 61 //1.获得NotificationManager 62 nmanager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 63 //2.创建Notification 64 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 发给 Manager 80 nmanager.notify(notificationID++, notification); 81 } 82 83 }
时间: 2024-10-20 16:42:00