[英]Sending notification from IntentService is not working?
我正在嘗試從 IntentService 發送通知。 我確實收到了所有日志,但沒有收到通知(使用我的 Galaxy s8 而不是模擬器)。
我嘗試擴展 Service 並嘗試使用調度程序,但兩者都不起作用。
服務代碼:
public class AppService extends IntentService {
private NotificationManager mNotificationManager;
public static final int NOTIFICATION_ID = 1;
public AppService() {
super("AppService");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.d("AppService", "Started");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
Log.d("AppService", "Sending notification");
sendNotification("We might have some brand new movies to offer you!");
Log.d("AppService", "Notification sent");
}
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Log.d("AppService", "1");
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, Analyze.class), 0);
Log.d("AppService", "2");
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setContentTitle("MyCienma")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setSmallIcon(R.drawable.icon_500x500_no_edge)
.setContentText(msg);
Log.d("AppService", "3");
mBuilder.setContentIntent(contentIntent);
Log.d("AppService", "4");
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Log.d("AppService", "5");
}
}
我確實收到了所有日志,但沒有收到任何通知。 我的項目的最低版本是 21,我的手機運行的是 26。這是一個問題嗎?
在 API v26 之后,您必須為每個通知定義一個 NotificationChannel
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default",
"YOUR_CHANNEL_NAME",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("YOUR_NOTIFICATION_CHANNEL_DISCRIPTION");
mNotificationManager.createNotificationChannel(channel);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.