import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
final static int NOT_ID = 0x111;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
creatNotify();
}
});
findViewById(R.id.btn2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancel(NOT_ID);
}
});
}
@RequiresApi(api = Build.VERSION_CODES.O)
void creatNotify() {
//指定一个ID,这个ID要和后面生成Channel ID一样,意思就是说这个通知放到将来在系统哪个频道发出。
// 这个ID是channel的ID
Notification.Builder builder = new Notification.Builder(this, "channel_id");
builder.setSmallIcon(R.drawable.tools);
builder.setContentTitle("标题")
.setTicker("this is ticker")
.setAutoCancel(true)
.setContentIntent(PendingIntent.getActivity(MainActivity.this, 1, new Intent(MainActivity.this, otherActivity.class), PendingIntent.FLAG_UPDATE_CURRENT));
Notification notification = builder.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//定义一个频道ID,这个频道用来发送跟这个频道对应ID一样的通知。
// 这个ID是channel的ID
NotificationChannel notificationChannel = new NotificationChannel("channel_id", "channel_name", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
// 这个ID的作用是为notification绑定一个ID,
// 是notification的在系统中的编号。为了后面删除该通知时调用这个ID
notificationManager.notify(NOT_ID, notification);
}
}