2016-02-20 103 views
1

使用GCM服務從節點js服務器發送消息,設備中的服務被接收到服務中,最後顯示在通知中。所有作品和設備都會收到通知,但是,當我想要創建通知時,它不會顯示通知。我很失落,也許我錯過了關於通知創建的內容。我正在用google提供的gcm示例來指導自己,儘管我不能顯示通知。從服務創建通知

這裏是服務的代碼:

public class MyGcmListenerService extends GcmListenerService { 

private static final String TAG = "MyGcmListenerService"; 
@Override 
public void onMessageReceived(String from, Bundle data) { 
    String message = data.getString("TableMeNot"); 
    Log.d(TAG, "From: " + from); 
    Log.d(TAG, "Message: " + message); 
    sendNotification(message); 

} 
private void sendNotification(String message) { 
    Intent intent = new Intent(this, MainActivity.class); 
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 
      PendingIntent.FLAG_UPDATE_CURRENT); 

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
      .setContentTitle("You have a new notification!!!") 
      .setContentText(message) 
      .setContentIntent(pendingIntent); 
    NotificationManager notificationManager = 
      (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 

    notificationManager.notify(1, notificationBuilder.build()); 
    Log.d(TAG, "NOTIFICATION CREATED!!!!!!!!!!!!!!!"); 
} 

感謝您的幫助。

+0

請問你的服務器端代碼的樣子?你如何發送通知? –

回答

0

試試這個

private void sendNotification() { 
     NotificationCompat.Builder mBuilder = 
       new NotificationCompat.Builder(this) 
         .setSmallIcon(R.drawable.ic_stat_msg_box_copy) 
         .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) 
         .setContentTitle(getResources().getString(R.string.app_name)) 
         .setColor(getResources().getColor(R.color.colorPrimary)) 

         .setContentText("New message"); 

     mBuilder.setAutoCancel(true); 

     Intent resultIntent = new Intent(this, MainActivity.class); 

     TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); 
     stackBuilder.addParentStack(MainActivity.class); 
     stackBuilder.addNextIntent(resultIntent); 
     PendingIntent resultPendingIntent = 
       stackBuilder.getPendingIntent(
         (int) System.currentTimeMillis(), 
         PendingIntent.FLAG_UPDATE_CURRENT 
       ); 
     mBuilder.setContentIntent(resultPendingIntent); 
     NotificationManager mNotificationManager = 
       (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
     mNotificationManager.notify(0, mBuilder.build()); 
    } 
+0

沒有工作,也許有必要在清單中指定關於服務的內容? –

+0

我的意思是,服務可以創建通知? –

+0

是你的服務工作嗎?你有沒有在manifest.xml中提到你的服務? –