android8.0以上版本区别与android7.0通知的出差距是,以上的版本必须添加渠道NotificationChannel 所以创建通知之前需要对android 的版本做一个判断
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
如果要设置手机的震动还的在清单文件中声明权限
<uses-permission android:name="android.permission.VIBRATE"/>
NotificationChannel 构造函数
NotificationChannel(String id,CharSequence name, int importance)
三个参数分别为ID,名字,重要度
几个重要度:
- IMPORTANCE_NONE 关闭通知
- IMPORTANCE_MIN 开启通知,不会弹出,但没有提示音,状态栏中无显示
- IMPORTANCE_LOW 开启通知,不会弹出,不发出提示音,状态栏中显示
- IMPORTANCE_DEFAULT 开启通知,不会弹出,发出提示音,状态栏中显示
- IMPORTANCE_HIGH 开启通知,会弹出,发出提示音,状态栏中显示
public class MainActivity extends AppCompatActivity {
private Button button;
private static final int ID = 2;
private static final String CHANNELID ="1";
private static final String CHANNELNAME = "channel1";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button= (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// manager.cancel(1);
//安卓8.0以上弹出通知需要添加渠道NotificationChannel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
//创建渠道
NotificationChannel channel = new NotificationChannel(CHANNELID,CHANNELNAME,NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(channel);//开启渠道
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,0,intent,0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this,CHANNELID);
builder .setContentTitle("Title")//通知标题
.setContentText("ContentText")//通知内容
.setWhen(System.currentTimeMillis())//通知显示时间
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.smile)
.setAutoCancel(true)//点击通知取消
//.setSound()
//第一个参数为手机静止时间,第二个参数为手机震动时间,周而复始
.setVibrate(new long[] {0,1000,1000,1000})//手机震动
//第一个参数为LED等颜色,第二个参数为亮的时长,第三个参数为灭的时长
.setLights(Color.BLUE,1000,1000)
/**表示通知的重要程度
* RIORITY_DEFAULT
* RIORITY_MIN
* RIORITY_LOW
* RIORITY_HIGE
* RIORITY_MAX
**/
.setPriority(NotificationCompat.PRIORITY_MAX)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.smile)).build();
manager.notify(1,builder.build());
} else{
Notification notification = new NotificationCompat.Builder(MainActivity.this)
.setContentTitle("Title")
.setContentText("ContentText")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.smile)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.smile))
.build();
manager.notify(1,notification);
}
}
});
}
}