1. android 8.0 之前通知 Notification.Builder、
参考博客:https://blog.csdn.net/qi85481455/article/details/82895507
基本案例:
public void sendNotification(View view){
// 设置点击通知启动 意图
// Intent intent = new Intent(this,MainActivity.class);
Intent intent = new Intent(); // 通过通知意图启动拨打电话界面
intent.setAction(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+110));
PendingIntent pi = PendingIntent.getActivity(MainActivity.this,0,intent,0);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder=new Notification.Builder(this);
builder.setContentTitle("小标题");
builder.setContentText("通知内容");
builder.setSmallIcon(R.mipmap.ic_launcher); // 小图标
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher)); // 大图标
builder.setWhen(System.currentTimeMillis()); //设置时间
builder.setAutoCancel(true); // 点击启动Activity以后自动取消
builder.setContentIntent(pi);
Notification nf=builder.build();
nf.flags= Notification.FLAG_INSISTENT; // 设置以后通知栏不能被取消,不起作用????
manager.notify(1,nf); // 1 是通知id 可以根据1 取消通知
}
2. andorid 8.0 以后通知
参考郭神博客:https://blog.csdn.net/guolin_blog/article/details/79854070
android 8.0 系统通知问题:通知不能分类,如果关闭通知栏开关以后,那么所有的通知都不能收到
android 8.0引入到了通知渠道概念,通知分组
比如把 有聊天 消息、订阅消息,把 聊天消息放入放入一个通知渠道 ,设置高优先级,
那么这个时候可以关闭订阅消息通知,
还可以在通知栏中右滑,设置 再次显示通知时间, 通知通知开关对这个类别
基本案例:
package com.notificationdemo.denganzhi;
import android.annotation.TargetApi;
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.opengl.Visibility;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
String channelId1 = "chat";
String channelId2 = "subscribe";
// 1. 创建通知渠道
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelName = "聊天消息";
/***
* 通知等级:
* NotificationManager.IMPORTANCE_HIGH;
* IMPORTANCE_DEFAULT
* IMPORTANCE_LOW
* IMPORTANCE_MIN
*/
int importance = NotificationManager.IMPORTANCE_HIGH;
createNotificationChannel(channelId1, channelName, importance);
channelName = "订阅消息";
importance = NotificationManager.IMPORTANCE_LOW;
createNotificationChannel(channelId2, channelName, importance);
}
}
@TargetApi(Build.VERSION_CODES.O)
private void createNotificationChannel(String channelId, String channelName, int importance) {
NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
channel.setShowBadge(true); // 允许显示角标
NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
// 2. 发送 聊挺通知 ,使用 channelId1 聊天渠道
public void sendNotifiction1(View view){
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new NotificationCompat.Builder(this, channelId1)
.setContentTitle("收到一条聊天消息")
.setContentText("今天中午吃什么?")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setAutoCancel(true)
.setNumber(1000) // 未读消息
.build();
manager.notify(1, notification);
}
// 3. 发送 订阅通知,使用通知渠道 channelId2
public void sendNotifiction2(View view){
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new NotificationCompat.Builder(this, channelId2)
.setContentTitle("发送一条订阅消息")
.setContentText("地铁10号线商铺抢购中!!!!")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setAutoCancel(true)
.build();
manager.notify(2, notification);
}
}
问题: 如果用户关闭聊天通知开关,那么用户无法使用通知,动态判断通知栏
package com.notificationdemo.denganzhi;
import android.annotation.TargetApi;
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.opengl.Visibility;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
String channelId1 = "chat";
// 1. 创建通知渠道
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelName = "聊天消息";
/***
* 通知等级:
* NotificationManager.IMPORTANCE_HIGH;
* IMPORTANCE_DEFAULT
* IMPORTANCE_LOW
* IMPORTANCE_MIN
*/
int importance = NotificationManager.IMPORTANCE_HIGH;
// 只会调用一次,系统有优化
createNotificationChannel(channelId1, channelName, importance)
}
}
@TargetApi(Build.VERSION_CODES.O)
private void createNotificationChannel(String channelId, String channelName, int importance) {
NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
channel.setShowBadge(true); // 允许显示角标
NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
public void sendNotifiction3(View view){
/**
* 如果 channelId1 通知渠道开关关闭,
* 比如聊天 功能无法使用
* 可以通过 Api判断 改通知去掉 开关状态,
* 如果用户关闭,那么手动去打开
*/
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = manager.getNotificationChannel(channelId1);
// 获取通知 渠道配置 IMPORTANCE_NONE 表示 关闭通知渠道了
if (channel.getImportance() == NotificationManager.IMPORTANCE_NONE) {
Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
intent.putExtra(Settings.EXTRA_CHANNEL_ID, channel.getId());
startActivity(intent);
Toast.makeText(this, "请手动将通知打开", Toast.LENGTH_SHORT).show();
}
}
}
}
3. android8.0 Serivice服务适配
启动服务:
MyService bleService=null;
/* 服务启动 */
public void showMsg(View view){
// 启动服务
Intent intent = new Intent(MainActivity.this,MyService.class);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
// android 8.0 启动服务,启动服务以后再5S内必须要调用 startForeground(1, notification);
// 否则抛出异常
startForegroundService(intent);
} else {
// android8.0 之前启动服务
startService(intent);
}
bindService(intent, new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
if (service instanceof MyService.MyBinder) {
MyService.MyBinder binder = (MyService.MyBinder) service;
bleService = binder.getService();
Log.e("denganzhi","服务启动成功 " + (bleService == null) );
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}, Context.BIND_AUTO_CREATE);
}
// 调用绑定服务中的方法
public void clickServiceMethod(View view){
bleService.showHello();
}
AndroidManifest.xml 配置
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"></service>
MyService.java
public class MyService extends Service {
private static final String TAG = "denganzhi";
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
return new MyBinder();
}
public class MyBinder extends Binder {
public MyService getService() {
return MyService.this;
}
}
public void showHello(){
Log.e("denganzhi","showHello :showHello" );
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, final int startId) {
int type = intent.getIntExtra("type",1);
Log.e(TAG, "the create notification type is " + type + "----" + (type == 1 ? "true" : "false"));
// 发送基本通知
// createNotificationChannel0001
//Android 图片产长图、大图通知;https://blog.csdn.net/SDBX_lyp/article/details/80157222
createNotificationChannel();;
return super.onStartCommand(intent, flags, startId);
}
// 普通通知,只有title 和 context , 一行内容无法展开
private void createNotificationChannel0001() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Log.e(TAG, "createNotificationChannel");
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 通知渠道的id
String id = "kaadas";
// 用户可以看到的通知渠道的名字.
CharSequence name = "Bluetooth lock notifications";
// 用户可以看到的通知渠道的描述
String description = "If you are using a Bluetooth lock, do not turn off notifications";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
// 配置通知渠道的属性
mChannel.setDescription(description);
// 设置通知出现时的闪灯(如果 android 设备支持的话)
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
// 设置通知出现时的震动(如果 android 设备支持的话)
// mChannel.enableVibration(true);
/// mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
// 最后在notificationmanager中创建该通知渠道 //
mNotificationManager.createNotificationChannel(mChannel);
// 为该通知设置一个id
// int notifyID = 1;
// 通知渠道的id
// String CHANNEL_ID = "my_channel_01";
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(this)
// .setContentTitle("通知栏Title") .setContentText("通知栏Text")
.setContentTitle("Bluetooth lock notifications").
setContentText("If you are using a Bluetooth lock, do not turn off notifications")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setChannelId(id)
.build();
startForeground(1, notification);
}
}
/**
* Android 图片产长图、大图通知;https://blog.csdn.net/SDBX_lyp/article/details/80157222
*
*/
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Log.e("denganzhi1", "createNotificationChannel");
android.app.NotificationManager mNotificationManager = (android.app.NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 通知渠道的id
String id = "kaadas";
// 用户可以看到的通知渠道的名字.
CharSequence name = "Bluetooth lock notifications";
// 用户可以看到的通知渠道的描述
String description = "If you are using a Bluetooth lock, do not turn off notifications";
int importance = android.app.NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
// 配置通知渠道的属性
mChannel.setDescription(description);
// 设置通知出现时的闪灯(如果 android 设备支持的话)
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
// 设置通知出现时的震动(如果 android 设备支持的话)
// mChannel.enableVibration(true);
/// mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
// 最后在notificationmanager中创建该通知渠道 //
mNotificationManager.createNotificationChannel(mChannel);
// 为该通知设置一个id
// int notifyID = 1;
// 通知渠道的id
// String CHANNEL_ID = "my_channel_01";
// Create a notification and set the notification channel.
Intent startIntent = new Intent(this,MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this,0,startIntent,0);
Notification notification = new NotificationCompat.Builder(this)
// .setContentTitle("通知栏Title") .setContentText("通知栏Text")
// .setContentTitle("通知栏Title") .setContentText("通知栏Text"
.setContentTitle(getString(R.string.kaadas_notification))
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
.setChannelId(id)
.setContentIntent(pi)
.setOnlyAlertOnce(true)
.setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.kaadas_notification_open)))
.build();
startForeground(1, notification);
}
}
@Override
public void onDestroy() {
super.onDestroy();
stopForeground(true);
}
}