2017-07-25 49 views
0

我目前正在開發一個應用程序,您可以在其中創建自己的通知(僅供參考)。你可以用(幾乎)任何方式來定製它們。將數據發送到通知

我的問題是:我不知道如何從主要活動獲取數據到我的通知服務。

這是怎麼了,我現在使用的目的是尋找像:

Intent startNotificationServiceIntent = new Intent(MainActivity.this, Notification.class); 
      startNotificationServiceIntent 
        .putExtra("Title", title) 
        .putExtra("Text", text) 
        .putExtra("Millis", millis) 
        .putExtra("IsImportant", isImportant); 

      startService(startNotificationServiceIntent); 

這是onStartCommand現在:

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    displayNotification(/*Currently empty*/); 
    stopSelf(); 
    return super.onStartCommand(intent, flags, startId); 
} 

這是方法(displayNotification)我用來創建通知:

private void displayNotification(String title, String text, long VibrationLongMillis, boolean isImportant) { 
    Intent notificationIntent = new Intent(this, MainActivity.class); 
    PendingIntent notificationPendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 

    NotificationCompat.Builder notification = new NotificationCompat.Builder(this) 
      .setContentTitle(title) 
      .setContentText(text) 
      .setSmallIcon(R.drawable.attention) 
      .setColor(getResources().getColor(R.color.colorPrimary)) 
      .setVibrate(new long[]{0, VibrationLongMillis, VibrationLongMillis, VibrationLongMillis}) 
      .setSound(uri) 
      .setContentIntent(notificationPendingIntent) 
      .setAutoCancel(true) 
      .setPriority(NotificationCompat.PRIORITY_DEFAULT) 
      .setStyle(new NotificationCompat.BigTextStyle().bigText(text)); 

    if (isImportant) { 
     notification.setPriority(NotificationCompat.PRIORITY_HIGH); 
    } 


    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
    notificationManager.notify(NOTIFICATION_ID, notification.build()); 

} 
+0

你想發送什麼數據?請更具描述性 – ZeekHuge

回答

0

您只需要將信息傳遞給Intent(正如你已經這樣做),然後在你的服務中這樣讀取它:

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    String title = intent.getStringExtra("Title"); 
    /* Do here the same for the other parameters */ 
    displayNotification(title, text, vibrationLongMillis, isImportant); 
    stopSelf(); 
    return super.onStartCommand(intent, flags, startId); 
} 
+0

完全重讀,謝謝:) – 2Simpel