2021-5-10
今天在写一个题目的时候发现书上的案例不太行,太老了。android8.0用不了书上的例子,我自己简单写了一下,但是发现怎么改都没有办法跳出通知。心态直接爆炸。
然后找了半天,整整半天,终于解决了。
package com.example.myapplication;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
public class MainActivity extends AppCompatActivity{
private static final int NOTIFICATION_FLAG = 1;
private Button btn1,btn2;
private NotificationManager notificationManager;
private PendingIntent pendingIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
btn1 = (Button)findViewById(R.id.btn1);
btn2 = (Button)findViewById(R.id.btn2);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//使用Notification.Builder()会出现划线,所以用下面这个方法
Notification notify = new NotificationCompat.Builder(MainActivity.this,"channelid1")
.setSmallIcon(R.drawable.shoucang)
.setTicker("小提示")
.setContentTitle("消息")
.setContentText("..........")
.build();
//下面这段代码搞了我整整半天,终于给我找到了。加了这段代码之后终于终于能运行了。
if(Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){
//只在Android 8.O之上需要渠道
NotificationChannel notificationChannel = new NotificationChannel("channelid1","channelname",NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
}
notify.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1,notify);
}
});
//下面这段我用的是书上的代码
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
notificationManager.cancel(NOTIFICATION_FLAG);//清除ID为NOTOFICATION_FLAG的通知
// notificationManager.cancelAll();
}
});
}
}