Notification有两种视觉风格,一种是标准视图(Normal View),另外一种是大视图(Big view)。标准视图在Android中各版本是通用的,但是对于大视图而言,仅支持Android4.1+的版本。
可以先运行以下代码查看一下android版本
int currentApiVersion = android.os.Build.VERSION.SDK_INT;
String androidVersion = android.os.Build.VERSION.RELEASE;
Log.d("手机版本", "API Level: " + currentApiVersion + ", 版本: " + androidVersion);
另外注意一点!如果运行了以下代码却没有接收到状态栏的通知,打开手机设置中的“通知与状态栏”这一项,点击“通知管理”,打开你的显示通知,因为一般情况下是默认关闭通知的。
布局页面
<Button
android:id="@+id/show_notification_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="点我通知"
android:layout_centerInParent="true"/>
package com.example.mqttrun;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
public class StatusNotification extends AppCompatActivity {
private static final String CHANNEL_ID = "my_channel";
private static final int NOTIFICATION_ID = 101;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
int currentApiVersion = android.os.Build.VERSION.SDK_INT;
String androidVersion = android.os.Build.VERSION.RELEASE;
Log.d("手机版本", "API Level: " + currentApiVersion + ", 版本: " + androidVersion);
Button showNotificationButton = findViewById(R.id.show_notification_button);
showNotificationButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showNotification();
}
});
createNotificationChannel();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "My Channel";
String description = "This is my notification channel";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
private void showNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("通知") //设置标题
.setContentText("您有新的设备故障警情,请注意查收!!!!") //设置通知文字
.setSubText("--俺们那疙瘩都是活雷锋")
.setWhen(System.currentTimeMillis()) //时间
.setSmallIcon(R.drawable.bj) //设置左边的小图标
//.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.message)) //设置大图标
.setDefaults(Notification.DEFAULT_ALL); //添加默认震动、声音、三色灯三种提醒
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
}
看一下最后效果: