一般只有当程序进入到后台的时候我们才需要使用通知。
步骤:
①创建一个NotificationManager来对通知进行管理(getSystemService()获取实例)
②使用Builder构造器来创建一个Notification对象(使用V4包),最后都要调用build()方法
③调用NotificationManager的notify()方法
④点击效果的实现pendingIntent。需要实例化和设置setContentIntent()方法
⑤取消通知栏setAutoCancel()和cancle()取消
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button send_notice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send_notice = (Button)findViewById(R.id.send_notice);
send_notice.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.send_notice:
Intent intent = new Intent(this, NotificationActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("This is content title")//标题栏
.setContentText("This is content text")//内容
.setWhen(System.currentTimeMillis())//被创建的时间
.setSmallIcon(R.drawable.recommend)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.recommend))
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(BitmapFactory.decodeResource(getResources(),R.drawable.app_icon)))
.setPriority(NotificationCompat.PRIORITY_MAX)//设置优先级
.setSound(Uri.fromFile(new File("/storage/emulated/0/iFlyIME/plugin/enable/EFACDBD6-64A1-EF28-47C1-E3AD81B71811/res/sound/超级玛丽.mp3")))//设置声音
.setLights(Color.GREEN,1000,1000) //设置LED灯
.setVibrate(new long[]{0,1000,0})//设置震动效果
// .setDefaults(NotificationCompat.DEFAULT_ALL)
.build();
manager.notify(1,notification);
break;
default:
break;
}
}
}
public class NotificationActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(1);
}
}