点击按钮,通知栏出现通知标志
代码如下:
package com.example.notificationtest;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendNotice=(Button)findViewById(R.id.send_notice);
sendNotice.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,NotificationActivity.class);
PendingIntent pi=PendingIntent.getActivity(getApplicationContext(),0,intent,0);
NotificationChannel channel = new NotificationChannel("1",
"Channel1", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
Notification notification=new NotificationCompat.Builder(getApplicationContext(),"1")
.setContentTitle("This is contenttitle")
.setContentText("This is content text")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
.setContentIntent(pi).build();
manager.notify(1,notification);
}
});
}
}
1、首先创建一个NotificationChannel实例
NotificationChannel channel = new NotificationChannel("1",
"Channel1", NotificationManager.IMPORTANCE_DEFAULT);
// * IMPORTANCE_NONE 关闭通知
// * IMPORTANCE_MIN 开启通知,不会弹出,但没有提示音,状态栏中无显示
// * IMPORTANCE_LOW 开启通知,不会弹出,不发出提示音,状态栏中显示
// * IMPORTANCE_DEFAULT 开启通知,不会弹出,发出提示音,状态栏中显示
// * IMPORTANCE_HIGH 开启通知,会弹出,发出提示音,状态栏中显示
前两个参数分别代表:channel的id,channel的名字
2、然后创建一个NotificationManager实例,并调用createNotificationChannel把channel传给这个实例
NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
3、创建一个Notification实例,然后设置通知的大小图标、文本、点击跳转事件等等,最后用manager调用notify()方法,传入两个参数:通知的id和通知。通知的id只要是唯一的就可以
Notification notification=new NotificationCompat.Builder(getApplicationContext(),"1")
.setContentTitle("This is contenttitle")
.setContentText("This is content text")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
.setContentIntent(pi).build();
manager.notify(2,notification);