在一个Activity中点击按钮,产生一个通知栏消息通知。
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")); } }
运行效果: