1. 程式人生 > >Android---訊息通知Notifycation

Android---訊息通知Notifycation

程式碼:

public class MainActivity extends AppCompatActivity {
    private final int NOTIFY_ID = 0x123;            //通知的ID
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //獲取通知管理器,用於傳送通知
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); NotificationCompat.Builder notification = new NotificationCompat.Builder(MainActivity.this); // 建立一個Notification物件 // 設定開啟該通知,該通知自動消失 notification.setAutoCancel(true
); // 設定顯示在狀態列的通知提示資訊 notification.setTicker("subtitle"); // 設定通知的小圖示 notification.setSmallIcon(R.mipmap.ic_launcher); //設定下拉列表中的大圖示 notification.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher)); // 設定通知內容的標題 notification.setContentTitle("ContentTitle"
); // 設定通知內容 notification.setContentText("點選檢視詳情!"); //設定傳送時間 notification.setWhen(System.currentTimeMillis()); // 建立一個啟動其他Activity的Intent Intent intent = new Intent(MainActivity.this , NotifyActivity.class); PendingIntent pi = PendingIntent.getActivity( MainActivity.this, 0, intent, 0); //設定通知欄點選跳轉 notification.setContentIntent(pi); //傳送通知 notificationManager.notify(NOTIFY_ID, notification.build()); } }

在android8.0的機子裡不會彈出通知,,會彈出一個toast,

Developer warning for package “xxx.xxx.xxx”
Failed to post notification on channel “xxx”
See log for more details

還會報錯:

NotificationService: No Channel found for pkg=com.example.xxx.notifydemo, channelId=null, id=291, tag=null, opPkg=com.example.xxx.notifydemo, callingUid=10074, userId=0, incomingUserId=0, notificationUid=10074, notification=Notification(channel=null pri=0 contentView=null vibrate=null sound=null tick defaults=0x0 flags=0x10 color=0x00000000 vis=PRIVATE)

解決方法:https://blog.csdn.net/rentee/article/details/78303532