3

我在我的android應用程序中實現了GCM,它在接收消息時工作正常。 根據Google提供的示例,BroadcastReceiver在清單文件中設置。活動監聽器 - Google Cloud Messaging - BroadcastReceiver

我的問題是:如果用戶具有應用程序打開,我要更新一些成果在該視圖 - 如何才能做到這一點?我首先想到在BroadCastReceiver收到的任何事情上將此活動註冊爲監聽者。但是,這必須是一個靜態的偵聽器列表,因爲BroadcastReceiver的新實例將被設置 - 但也許這不是這樣做的方式。

這是我目前有

 public class GCMBroadcastReceiver extends WakefulBroadcastReceiver { 

      @Override 
      public void onReceive(Context context, Intent intent) { 
       ComponentName comp = new ComponentName(context.getPackageName(), 
         GCMIntentService.class.getName()); 
       startWakefulService(context, (intent.setComponent(comp))); 
       setResultCode(Activity.RESULT_OK); 
      } 
     } 


     public class GCMIntentService extends IntentService { 
      public static final int NOTIFICATION_ID = 1; 
      private NotificationManager mNotificationManager; 
      NotificationCompat.Builder builder; 

      public GCMIntentService() { 
       super("GCMIntentService"); 
      } 

      @Override 
      protected void onHandleIntent(Intent intent) { 
       Bundle extras = intent.getExtras(); 
       GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); 
       String messageType = gcm.getMessageType(intent); 

       if (!extras.isEmpty()) { 
        if (GoogleCloudMessaging. 
          MESSAGE_TYPE_MESSAGE.equals(messageType)) { 

        /** How to check if the activity 
GameActivity is running, and hence send an 
update signal to it? If it's not running a 
notification should be created. 
    **/ 
        } 
       } 
       GCMBroadcastReceiver.completeWakefulIntent(intent); 
      } 
     } 

這裏的重要組成部分,這在清單文件:

 <receiver 
      android:name="q.w.e.gcm.GCMBroadcastReceiver" 
      android:permission="com.google.android.c2dm.permission.SEND" > 
      <intent-filter> 
       <action android:name="com.google.android.c2dm.intent.RECEIVE" /> 

       <category android:name="q.w" /> 
      </intent-filter> 
     </receiver> 

     <service android:name="q.w.e.gcm.GCMIntentService" /> 

有什麼建議?

謝謝!

回答

3

有兩種處理方法。

1.檢查活動是否正在運行。

ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); 
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1); 
ComponentName componentInfo = taskInfo.get(0).topActivity; 
if(componentInfo.getPackageName().equalsIgnoreCase("com.yourpackagename")){ 
    //Activity Running 
    Send a broadcast with the intent-filter which you register in your activity 
    where you want to have the updates 
} 
else{ 
    //Activity Not Running 
    //Generate Notification 
} 

2.使用SendOrderedBroadcast

blog會給你這到底是怎麼實現的想法。

+0

我剛剛更新了一些最小化代碼的問題,看它的樣子。假設我有一個名爲GameActivity的活動。使用上面的代碼,如果這個活動正在運行,我會知道它的名字。但是,我該如何將它廣播到正在運行的實例呢? – moviaa

+0

您在GameActivity的onResume中註冊一個廣播接收器並在OnPause中取消註冊,然後您只需使用sendBroadcast方法廣播意圖。如果它正在運行,您的活動將能夠捕捉廣播。 :) –