1. 有关Notification的详解
http://www.2cto.com/kf/201502/374946.html
2. 案例
附上两个例子,,一个是开启一个通知, 另一个是开启一个服务,,甚至是主要代码:
public void btnBormalNotify(View view) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
// title, text, smallIcon 必须设置
builder.setContentTitle("通知")
.setContentText("内容")
.setSmallIcon(R.mipmap.ic_launcher);
// // 声音可以自定义
// Uri.fromFile()
// builder.setSound();
builder.setDefaults(Notification.DEFAULT_ALL);
Intent intent = new Intent(this, NewsActivity.class);
intent.putExtra("uri", "www.baidu.com");
// !!!使用通知的PendingIntent时,必须设置 Intent 的 FLAG, 针对于Activity
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pi =
PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pi);
Notification build = builder.build();
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this);
managerCompat.notify(998, build);
}
public void btnReceiver(View view) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle("通知")
.setContentText("内容")
.setSmallIcon(R.mipmap.ic_launcher);
builder.setDefaults(Notification.DEFAULT_ALL);
// !! 可以在通知中添加按钮点击操作
Intent intent = new Intent("com.xiaohong.ACTION_PLAY");
// 和在Intent里面设置Action同样的作用
//intent.setClassName(this, MyReceiver.class.getName());
// getBroadcast 内部会执行 sendBroadcast
PendingIntent piPlay
= PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(android.R.drawable.ic_media_play, "播放", piPlay);
Notification build = builder.build();
NotificationManagerCompat from = NotificationManagerCompat.from(this);
from.notify(999, build);
}