public class MainActivity extends AppCompatActivity {
private NotificationManager mNotifymanager;
// private static int REQUEST_CODE = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNotifymanager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
/**
* 打开通知 onclick绑定
*
* @param view
*/
public void startNotify(View view) {
/**
* getActivity 参数介绍
* 如果你没有用到Intent的extras,你不需要指定任何的flags
* 如果用到了Extra 系统按照下面方式进行处理extras
*
* 参数2:这个PendingIntent对象的标记 可以结合参数4使用 如果参数2固定 新通知会影响到旧通知
* 一般也用不到
*
*
* 参数4:FLAG_NO_CREATE:PendingIntent不存在则返回NULL
* FLAG_ONE_SHOT:PendingIntent只能用一次
* FLAG_CANCEL_CURRENT:后一个PendingIntent会替换前一个,让前一个不可用
* FLAG_UPDATE_CURRENT:后一个PendingIntent会更新前一个,让前一个和后一个内容变成一样
* FLAG_UPDATE_CURRENT这个用的比较多
*/
// REQUEST_CODE++;
Intent intent = new Intent();
intent.setClass(this, SecondActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//选择V7包下的类 兼容低版本
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("通知标题") //标题
.setContentText("通知内容" + timeFormate(System.currentTimeMillis())) //内容
.setWhen(System.currentTimeMillis()) //时间
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_round)) //大图标
.setSmallIcon(R.mipmap.ic_launcher) //小图标
.setContentIntent(pendingIntent) //设置延时意图 用来做通知的点击事件
.setAutoCancel(true) //设置点击一次后自动取消通知,默认false 通知点击后一直存在
.setLights(Color.BLUE, 2000, 2000) //手机头上的led灯
//设置通知的重要程度,这里设置了最高 但是在我的手机上依然弹出横幅 国内定制化ROM原因 只能手动去设置里面改
.setPriority(NotificationCompat.PRIORITY_MAX)
.build(); //返回一个通知对象
//其他的set设置看方法名就能猜到作用,震动需要配置权限
//可以通过mNotifymanager.cancel(0)来取消通知的显示(0就是notify方法里面的标识) 跟setAutoCancel(true)二选一使用
mNotifymanager.notify(0, notification); //管理者启动通知 参数1通知身份标识 每个通知都要唯一
}
/**
* 格式化时间
*/
@SuppressLint("SimpleDateFormat")
private static String timeFormate(Long time) {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time);
}
}
有错误欢迎指正