2017-06-20 106 views
5

我正在嘗試啓動前臺服務。我得到通知,服務確實開始,但通知總是被壓制。我仔細檢查了應用程序是否允許在我的設備上的應用程序信息中顯示通知。這裏是我的代碼:未顯示Android前臺服務通知

private void showNotification() { 
    Intent notificationIntent = new Intent(this, MainActivity.class); 
    notificationIntent.setAction(Constants.ACTION.MAIN_ACTION); 
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK 
      | Intent.FLAG_ACTIVITY_CLEAR_TASK); 
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, 
      notificationIntent, 0); 

    Bitmap icon = BitmapFactory.decodeResource(getResources(), 
      R.mipmap.ic_launcher); 

    Notification notification = new NotificationCompat.Builder(getApplicationContext()) 
      .setContentTitle("Revel Is Running") 
      .setTicker("Revel Is Running") 
      .setContentText("Click to stop") 
      .setSmallIcon(R.mipmap.ic_launcher) 
      //.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false)) 
      .setContentIntent(pendingIntent) 
      .setOngoing(true).build(); 
    startForeground(Constants.FOREGROUND_SERVICE, 
      notification); 
    Log.e(TAG,"notification shown"); 

} 

這裏是我的關係看到的唯一錯誤: 06-20 12:26:43.635 895-930/? E/NotificationService: Suppressing notification from the package by user request.

回答

10

問題是我使用的Android O和它需要更多的信息。這裏是Android的成功代碼。

mNotifyManager = (NotificationManager) mActivity.getSystemService(Context.NOTIFICATION_SERVICE); 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) createChannel(mNotifyManager); 
    mBuilder = new NotificationCompat.Builder(mActivity, "YOUR_TEXT_HERE").setSmallIcon(android.R.drawable.stat_sys_download).setColor 
      (ContextCompat.getColor(mActivity, R.color.colorNotification)).setContentTitle(YOUR_TITLE_HERE).setContentText(YOUR_DESCRIPTION_HERE); 
    mNotifyManager.notify(mFile.getId().hashCode(), mBuilder.build()); 

@TargetApi(26) 
private void createChannel(NotificationManager notificationManager) { 
    String name = "FileDownload"; 
    String description = "Notifications for download status"; 
    int importance = NotificationManager.IMPORTANCE_DEFAULT; 

    NotificationChannel mChannel = new NotificationChannel(name, name, importance); 
    mChannel.setDescription(description); 
    mChannel.enableLights(true); 
    mChannel.setLightColor(Color.BLUE); 
    notificationManager.createNotificationChannel(mChannel); 
} 
+0

有沒有更方便的方法來處理這個問題?即支持/兼容式?相同的代碼可以在26和26以上平臺上運行,不需要使用「if」和複製代碼。 –

+0

if(Build.VERSION.SDK_INT> = Build.VERSION_CODES.O){createNotificationChannel(context);} //代碼的其餘部分 –

+0

但是在這個新的代碼片段中,我注意到您正在調用'mNotifyManager.notify )'而不是'startForeground()'。在這種情況下,它是否真的使服務成爲前景? –

0

在我的情況下,它是由我使用IntentService引起的。

總之,如果你想要一個前臺服務,然後子類Service