2017-04-13 30 views
8

我目前正在開發一個Android項目。來自服務的運行活動中的調用方法

到目前爲止,我已經實現了火力地堡,特別是FirebaseInstanceIdService和FirebaseMessagingService:

public class FirebaseIDService extends FirebaseInstanceIdService { 
private static final String TAG = "FirebaseIDService"; 

private Context context; 

@Override 
public void onTokenRefresh() { 
    context = getApplicationContext(); 
    // Get updated InstanceID token. 
    String refreshedToken = FirebaseInstanceId.getInstance().getToken(); 
    Log.e(TAG, "Refreshed token: " + refreshedToken); 

    SharedPreferences sharedPreferences = context.getSharedPreferences("token", context.MODE_PRIVATE); 
    SharedPreferences.Editor editor = sharedPreferences.edit(); 
    editor.putString("token", refreshedToken); 
    editor.commit(); 

    sendRegistrationToServer(refreshedToken); 
} 

/** 
* Persist token to backend. 
* @param token The new token. 
*/ 
private void sendRegistrationToServer(String token) { 
    SendRegistrationKey task = new SendRegistrationKey(context); 
    task.execute(token); 
} 

}

public class MessagingService extends FirebaseMessagingService { 

private static final String TAG = "MsgService"; 

/** 
* Called when message is received. 
* 
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging. 
*/ 
@Override 
public void onMessageReceived(RemoteMessage remoteMessage) { 
    Log.e(TAG, "From: " + remoteMessage.getFrom()); 

    // Check if message contains a data payload. 
    if (remoteMessage.getData().size() > 0) { 
     Log.e(TAG, "Message data payload: " + remoteMessage.getData()); 
    } 

    // Check if message contains a notification payload. 
    if (remoteMessage.getNotification() != null) { 
     Log.e(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); 

     sendNotification(remoteMessage); 
    } 

    // Also if you intend on generating your own notifications as a result of a received FCM 
    // message, here is where that should be initiated. See sendNotification method below. 
} 
// [END receive_message] 

private void sendNotification(RemoteMessage remoteMessage) { 
    RemoteMessage.Notification notification = remoteMessage.getNotification(); 
    PushNotificationManager PNManager = PushNotificationManager.getInstance(getApplicationContext()); 
    PNManager.buildNotification(notification.getTitle(), notification.getBody()); 
} 

我想實現的是以下幾點:

當應用程序處於後臺時,我只想在通知中心進行簡單的通知。 (這已經在工作)

但是,當應用程序處於前臺並且正在運行時,我想要有不同的行爲: 我想消費推送通知並顯示警報。

但我的問題是:我如何與服務中的正在運行的活動進行交互,或者實現預期行爲的正確方式是什麼?熱爾必須是一個簡單的靈魂,對不對?

在此先感謝

+0

sendBroadcast從服務,並在活動中註冊自廣播接收機在活動

context.registerReceiver (myBroadcastReceiver, new IntentFilter ("CUSTOM_ACTION")); private final BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive (Context context, Intent intent) { //Do something } }; 

2.發送廣播收聽廣播 – X3Btel

回答

1

嘗試這樣的:

所有正在運行的應用這種方法檢查,當前應用程序是在後臺狀態或前臺狀態返回true或false。

public static 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

上述評判檢查正在運行的應用,並返回true或false,無論當前應用程序是處於後臺狀態還是處於前臺狀態 –

+0

哪些信息在哪裏? –

4

寫這段代碼的應用程序類

public Context currentactvity = null; 
public Context getCurrentactvity() { 
    return currentactvity; 
} 

public void setCurrentactvity(Context currentactvity) { 
    this.currentactvity = currentactvity; 
} 

寫這段代碼中的每個活動的onResume方法和在onPause方法設置爲null

// in onresume 
MyApplication.getInstance().setCurrentactvity(this); 

// in onpause 
MyApplication.getInstance().setCurrentactvity(null); 
現在

你可以從服務類呼叫活動的方法

if (MyApplication.getInstance().getCurrentactvity() != null && MyApplication.getInstance().getCurrentactvity() instanceof youractivityname) { 
      ((youractivityname) MyApplication.getInstance().getCurrentactvity()).youmethodname(parameter); 

     } 
+0

太棒了,那正是我想要的(y) –

2

我該如何與服務中的運行活動進行交互,或者實現預期行爲的正確方法是什麼?

最好的方法是簡單地使用事件總線(即GreenRobot'slocal broadcast)。您的活動在onResume()中註冊監聽者(並在onPause()註銷),並且您的服務只需在時間到來時廣播該消息。

最主要的好處是您可以將兩個元素(服務和活動)完全分開。您還避免了最糟糕的解決方案 - 直接調用Activity的方法。

要了解您是否處於後臺,最好使用應用程序的GreenRobot'sActivityLifecycleCallbacks - 強制活動沒有任何意義,因爲這完全沒有任何好處。

0

嘗試

1。從服務

Intent intent = new Intent ("CUSTOM_ACTION"); 
context.sendBroadcast (intent) 
+1

隱式廣播在Android O. –

+0

+1中不起作用。感謝更新。更新了答案。 「通過調用Context.registerReceiver()在運行時創建接收器,而不是在清單中聲明接收器。」 https://developer.android.com/preview/features/background.html#broadcasts – Pehlaj

相關問題