Android 《Notification》
代码
package com.xian.app.broadcast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private NotificationManager manager;
private Notification notification;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_send_notification).setOnClickListener(this);
findViewById(R.id.btn_close_notification).setOnClickListener(this);
initNotify();
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_send_notification:
manager.notify(1,notification); //ID要一致
break;
case R.id.btn_close_notification: // ID 要一致
manager.cancel(1);
break;
}
}
private void SendNotification() {
manager.notify(1,notification);
}
/***
* 发送Notification
*/
private static final String channelId = "xian";
private void initNotify() {
manager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
//兼容性处理
if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.O){
/**
* public static final int IMPORTANCE_NONE = 0;
* 关闭通知
* public static final int IMPORTANCE_MIN = 1;
* 开启通知,不会弹出,没有提示音,状态栏中没显示
* public static final int IMPORTANCE_LOW = 2;
* 开启通知,不会弹出,没有提示音,状态栏中有显示
* public static final int IMPORTANCE_DEFAULT = 3;
* 开启通知,不会弹出,发出提示音,状态栏中有显示
* public static final int IMPORTANCE_HIGH = 4;
* 开启通知,会弹出,发出提示音,状态栏中有显示
*/
NotificationChannel channel = new NotificationChannel(channelId, "测试通知", NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(channel);
}
Intent intent = new Intent(this,ReturnDeskActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//FLAG_ONE_SHOT, FLAG_NO_CREATE, FLAG_CANCEL_CURRENT, FLAG_UPDATE_CURRENT
PendingIntent pendingIntent = PendingIntent.getActivity(this,10086,intent,0);
notification = new NotificationCompat.Builder(this, channelId)
.setContentTitle("你有一个新的通知")
.setContentText("银行卡新收入500w人民币")
.setSmallIcon(R.drawable.ic_launcher_background)
.setColor(Color.parseColor("#ff0000"))
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher_foreground)) //设置大图标
.setContentIntent(pendingIntent) //点击通知后跳转PendingIntent
.setAutoCancel(true) //点击通知后是否自动取消
.build();
}
}
效果图
本文来自博客园,作者:一个小笨蛋,转载请注明原文链接:https://www.cnblogs.com/paylove/p/18066414