2017-02-18 188 views

回答

0

在您的通知收件人收到通知時,您可以檢查應用程序是否在後臺並做出相應顯示通知的決定。

這裏有一個代碼來檢查應用程序是否在後臺。

public class MyGcmPushReceiver extends GcmListenerService { 

    /** 
    * Called when message is received. 
    * @param from SenderID of the sender. 
    * @param bundle Data bundle containing message data as key/value pairs. 
    *    For Set of keys use data.keySet(). 
    */ 
    @Override 
    public void onMessageReceived(String from, Bundle bundle) { 
     // Check here whether the app is in background or running. 
     if(isAppIsInBackground(getApplicationContext())) { 
      // Show the notification 
     } else { 
      // Don't show notification 
     } 
    } 

     /** 
     * Method checks if the app is in background or not 
     */ 
     private boolean isAppIsInBackground(Context context) { 
      boolean isInBackground = true; 

      ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 
      if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) { 
       List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses(); 
       for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) { 
        if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { 
         for (String activeProcess : processInfo.pkgList) { 
          if (activeProcess.equals(context.getPackageName())) { 
           isInBackground = false; 
          } 
         } 
        } 
       } 
      } 
      else 
      { 
       List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1); 
       ComponentName componentInfo = taskInfo.get(0).topActivity; 
       if (componentInfo.getPackageName().equals(context.getPackageName())) { 
        isInBackground = false; 
       } 
      } 
      return isInBackground; 
     } 
} 
+0

我打電話給Method裏面onCreate活動?? @先生。兔子 –

+0

是來電是來自活動,但發佈在應用程序類 – user3040153

+0

@FinnD您需要在您的接收器,而不是在onCreate調用此方法。如果您使用的是GCM接收器,我已經編輯了可以顯示GCM接收器示例的答案。 –

相關問題