2014-09-25 35 views
0

我有一個在AndroidManifest.xml中聲明的應用程序範圍BroadcastReceiver。廣播在接收器中處理後,我想開始處理事件的活動。有兩個選項:更新活動,如果它正在運行,或者通知用戶它沒有運行(來自BroadcastReceiver)

a)如果目標活動正在運行,只需更新它; b)如果目標活動沒有運行,向用戶顯示通知,所以他可以點擊它並啓動活動。

但接收者不知道活動是否正在運行。我正在考慮在活動內部定義靜態變量running,該變量在onStart和中更新。但這是一個可靠的解決方案嗎?我猜不會。

什麼是最合適的方式?

+1

您是否檢查過[此鏈接](http://stackoverflow.com/questions/5446565/android-how-do-i-check-if-activity-is-running) – 2014-09-25 08:20:29

回答

0
public class MyBroadcastReceiver extends BroadcastReceiver 
    { 
public boolean checkApp; 

     @Override 
     public void onReceive(Context context, Intent intent) 
     { 
    for (RunningAppProcessInfo appProcess : appProcesses) { 
        if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND 
          && appProcess.processName 
            .equals("-------> Ur package ----> example--[com.emdsys.android.pacs]")) { 


         List<ActivityManager.RunningTaskInfo> taskInfo = activityManager 
           .getRunningTasks(1); 



         if (taskInfo.get(0).topActivity 
           .getClassName() 
           .toString() 
           .equals("-----> UR Activity Name-------(-ex)[com.emdsys.android.pacs.activity.TabActivityPacs]")) { 
checkApp = true; 

    //update ur activity what ever u want. 
         } 

         ComponentName componentInfo = taskInfo.get(0).topActivity; 
         componentInfo.getPackageName(); 

        } 
    } 
if(!checApp){ 

      Log.d("ME", "Notification started"); 
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, 
      new Intent(context, [ur Activity].class), 0); 

      NotificationCompat.Builder mBuilder = 
       new NotificationCompat.Builder(context) 
       .setSmallIcon(R.drawable.ic_launcher) 
       .setContentTitle("My notification") 
       .setContentText("Hello World!"); 
setContentIntent(contentIntent).build(); 

      NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
      mNotificationManager.notify(1, mBuilder.build()); 
} 
     } 
相關問題