2015-04-22 4 views
0

Как обновить макет при получении push-уведомления? я получаю класс:Обновить макет при получении push-уведомления

@Override 
    protected void onHandleIntent(Intent intent) { 
     Bundle extras = intent.getExtras(); 
     GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); 
     // The getMessageType() intent parameter must be the intent you received 
     // in your BroadcastReceiver. 
     String messageType = gcm.getMessageType(intent); 

     if (!extras.isEmpty()) { // has effect of unparcelling Bundle 
      /* 
      * Filter messages based on message type. Since it is likely that GCM will be 
      * extended in the future with new message types, just ignore any message types you're 
      * not interested in, or that you don't recognize. 
      */ 
      if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { 
       sendNotification("Send error: " + extras.toString()); 
      } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { 
       sendNotification("Deleted messages on server: " + extras.toString()); 
       // If it's a regular GCM message, do some work. 
      } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { 
       // This loop represents the service doing some work. 
       for (int i = 0; i < 5; i++) { 

        try { 
         Thread.sleep(5000); 
        } catch (InterruptedException e) { 
        } 
       } 
       // Post notification of received message. 
       message = extras.getString("message"); 
       badgeCount = extras.getString("badge"); 
       sendNotification("Received: " + extras.toString()); 
      } 
     } 
     // Release the wake lock provided by the WakefulBroadcastReceiver. 
     GcmBroadcastReceiver.completeWakefulIntent(intent); 
    } 

    // Put the message into a notification and post it. 
    // This is just one simple example of what you might choose to do with 
    // a GCM message. 
    private void sendNotification(String msg) { 

     int requestID = (int) System.currentTimeMillis(); 

     mNotificationManager = (NotificationManager)getApplication().getSystemService(Context.NOTIFICATION_SERVICE); 

     Intent notificationIntent = new Intent(getApplicationContext(), MainPageActivity.class); 

     notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); 

     PendingIntent contentIntent = PendingIntent.getActivity(this, requestID,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

     NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext()) 
       .setSmallIcon(R.drawable.icons) 
       .setContentTitle(getString(R.string.app_name)) 
       .setStyle(new NotificationCompat.BigTextStyle() 
         .bigText(message)) 
       .setContentText(message).setAutoCancel(true); 
     mBuilder.setContentIntent(contentIntent); 
     mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); 

     try { 
      if(Integer.parseInt(badgeCount) != 0) 
       ShortcutBadger.setBadge(getApplicationContext(), Integer.parseInt(badgeCount)); 
     } catch (ShortcutBadgeException e) { 
      //handle the Exception 
     } 


    } 

} 

, где я получаю толчок уведомление. Итак, когда я нахожусь в первой активности и получаю push-уведомление, я хочу обновить все эти действия. Это должно работать с 3-мя действиями, поэтому, когда я нахожусь во второй активности и получаю толчок, чтобы это второе действие должно воссоздать. Любые идеи, как я могу это сделать?

ответ

1

Вы можете сделать пользователю LocalBroadcastManager

ReceiverActivity.java

деятельность, которая следит за уведомлениями на мероприятие под названием «заказ событий имя».

@Override 
public void onCreate(Bundle savedInstanceState) { 

    ... 

    // Register to receive messages. 
    // We are registering an observer (mMessageReceiver) to receive Intents 
    // with actions named "custom-event-name". 
    LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, 
     new IntentFilter("custom-event-name")); 
} 

// Our handler for received Intents. This will be called whenever an Intent 
// with an action named "custom-event-name" is broadcasted. 
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
    // Get extra data included in the Intent 
    String message = intent.getStringExtra("message"); 
    Log.d("receiver", "Got message: " + message); 
    } 
}; 

@Override 
protected void onDestroy() { 
    // Unregister since the activity is about to be closed. 
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver); 
    super.onDestroy(); 
} 

SenderActivity.java

Вторая деятельность, которая отправляет уведомления/передачи.

@Override 
public void onCreate(Bundle savedInstanceState) { 

    ... 

    // Every time a button is clicked, we want to broadcast a notification. 
    findViewById(R.id.button_send).setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     sendMessage(); 
    } 
    }); 
} 

// Send an Intent with an action named "custom-event-name". The Intent sent should 
// be received by the ReceiverActivity. 
private void sendMessage() { 
    Log.d("sender", "Broadcasting message"); 
    Intent intent = new Intent("custom-event-name"); 
    // You can also include some extra data. 
    intent.putExtra("message", "This is my message!"); 
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent); 
} 

Вы можете отправить сообщение (SecondActivity.java) из onMessage метода вашего уведомления приемника.

+0

спасибо. Ваше решение идеально подходит для меня. – edi233