正如跟進凱文Krumwiede的已接受的答案,這裏有一些實施細節的一種可能的方式來跟隨他的做法(任何錯誤都是我的):
創建可重用的BroadcastReceiver
public class CurrentActivityReceiver extends BroadcastReceiver {
private static final String TAG = CurrentActivityReceiver.class.getSimpleName();
public static final String CURRENT_ACTIVITY_ACTION = "current.activity.action";
public static final IntentFilter CURRENT_ACTIVITY_RECEIVER_FILTER = new IntentFilter(CURRENT_ACTIVITY_ACTION);
private Activity receivingActivity;
public CurrentActivityReceiver(Activity activity) {
this.receivingActivity = activity;
}
@Override
public void onReceive(Context sender, Intent intent) {
Log.v(TAG, "onReceive: finishing:" + receivingActivity.getClass().getSimpleName());
if (<your custom logic goes here>) {
receivingActivity.finish();
}
}
}
實例化,並使用廣播接收器在每個活動的
public class MainActivity extends AppCompatActivity {
private BroadcastReceiver currentActivityReceiver;
@Override
protected void onResume() {
super.onResume();
currentActivityReceiver = new CurrentActivityReceiver(this);
LocalBroadcastManager.getInstance(this).
registerReceiver(currentActivityReceiver, CurrentActivityReceiver.CURRENT_ACTIVITY_RECEIVER_FILTER);
}
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).
unregisterReceiver(currentActivityReceiver);
currentActivityReceiver = null;
super.onPause();
}
}
最後,把你的FirebaseMessagingService內的適當廣播
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Intent localMessage = new Intent(CurrentActivityReceiver.CURRENT_ACTIVITY_ACTION);
LocalBroadcastManager.getInstance(MyApplication.this).
sendBroadcast(localMessage);
}
}
此代碼寄存器和註銷currentActivityReceiver以這樣的方式,以確保廣播接收機是活躍,只有when the Activity is active.
如果您有大量在您的應用程序活動,你可能要創建一個抽象基類的活動,並把和的onResume在onPause代碼是,和你的其他活動從類繼承。
您還可以將數據添加到onMessageReceived(例如localMessage.putExtra())中名爲「localMessage」的Intent中,並稍後在接收器中檢索該數據。凱文的回答
一個優勢是,他的方法不需要任何額外的權限(如GET_TASKS)。另外,正如Kevin指出的那樣,除了BroadcastReceiver之外,還有其他更便捷的方式來傳遞消息(例如EventBus和Otto)。恕我直言,這些都很好,但他們需要一個額外的庫,這將增加一些方法計數開銷。而且,如果您的應用程序已經在很多其他地方使用BroadcastReceivers,則出於審美和維護的原因,您可能會覺得您不希望在應用程序中傳遞消息。 (也就是說,EventBus非常酷,我感覺它比BroadcastReceivers更簡單。)
謝謝!我嘗試了代碼。兩個問題:(1)getRunningTasks已被棄用。 (2)我如何讓活動完成()它? – ikevin8me
是你的應用程序的活動或可能是任何應用程序? – jagapathi
我得到的活動名稱(即組件名稱)正是我想要的/預期的。現在我需要完成()它。我怎麼做? – ikevin8me