在一個Activity中點擊按鈕,產生一個通知欄消息通知。android
package cn.luxh.mynotice; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; public class MainActivity extends Activity { private static String TAG = "MyNotice"; private static int notificationID = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); handleBtnDisplayNotification(); } /** * 點擊按鈕,建立消息通知 */ private void handleBtnDisplayNotification() { Button btnDisplayNotification = (Button) findViewById(R.id.btn_display_notice); btnDisplayNotification.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.i(TAG, "點擊按鈕"); Intent i = new Intent(MainActivity.this,NoticeViewActivity.class); i.putExtra("notificationID", notificationID); PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, i, 0); NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); //建立通知對象 Notification n = new Notification.Builder(MainActivity.this) .setContentTitle("有來自黑莓的新郵件") .setContentText("黑莓,依然經典!") .setSmallIcon(R.drawable.ic_launcher) .setContentIntent(pi) .build(); //振動手機 n.vibrate = new long[]{100,250,100,500}; nm.notify(notificationID, n); } }); } }
package cn.luxh.mynotice; import android.app.Activity; import android.app.NotificationManager; import android.os.Bundle; import android.util.Log; /** * 在通知欄點擊通知後顯示消息的界面 * @author Luxh * */ public class NoticeViewActivity extends Activity{ private static String TAG = "MyNotice"; @Override protected void onCreate(Bundle savedInstanceState) { Log.i(TAG, "NoticeViewActivity onCreate"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_notice_view); NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); //取消通知 nm.cancel(getIntent().getExtras().getInt("notificationID")); } }
運行效果:app