notification通知应用UI之外的消息并显示即推送;
NotificationManager负责管理通知,例如显示取消,删除等;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public Button button1,btn2;
String channelId ="001" ;//这个东西是特定的
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 =findViewById(R.id.btn1);
btn2 =findViewById(R.id.btn2);
button1.setOnClickListener(this);
btn2.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn1:
showCommon();
break;
case R.id.btn2:
break;
}
}
public void showCommon() {
// Android 8.0之后,需要手动添加NotifacationChannel实现
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel("001", "channel_name", NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(notificationChannel);
}
//第一步创建一个builder对线作为通知对象
NotificationCompat.Builder builder=new NotificationCompat.Builder(this,channelId);
//第二步设置builder的一些参数
builder.setSmallIcon(R.mipmap.ic_launcher);//设置通知的小图标
builder.setContentTitle("通知标题");//设置通知的标题
builder.setContentText("通知内容");//设置通知的内容
builder.setDefaults(Notification.DEFAULT_ALL);//设置通知的默认效果,例如震动,铃声等
builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);//设置通知的优先级
builder.setAutoCancel(true);//设置通知被点击后自动消失
builder.setWhen(System.currentTimeMillis());//设置通知产生的时间
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher));//设置通知的大图标
//第三步显示
notificationManager.notify(001,builder.build());
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="显示一个通知"
android:id="@+id/btn1"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="显示"
android:id="@+id/btn2"/>
</LinearLayout>
标签:NotificationManager,notification,builder,笔记,通知,import,Android,android,btn2 From: https://blog.csdn.net/2303_76230584/article/details/137248334