[英]Distinct communication from Android Library Project to App using it
誰能告訴我從Android庫項目到使用該庫的應用進行通信的好方法嗎?
簡要說明:我的圖書館收到GCM通知,並使用此圖書館將其中的一些轉發給App。 現在,我通過庫發送的Intents和在App中監聽該Intent的BroadcastReceiver意識到了這一點。
問題是:當我在自己的應用程序中安裝2個Apps時,兩者都會收到彼此的通知。 有人有主意嗎?
提前致謝!
[編輯]
這是一些代碼。 我在庫中收到GCM通知,並將其轉發到使用中的應用程序:
GCMIntentService:
@Override
protected void onHandleIntent(Intent intent) {
...
String notificationString = intent
.getStringExtra(GCMConstants.NOTIFICATION);
Intent broadIntent = new Intent(getResources().getString(
R.string.con_broadcast_gcm_notification));
broadIntent.putExtra("callback", notification.getCallback());
context.sendBroadcast(broadIntent);
...
}
我的BroadcastReceiver會監聽con_broadcast_gcm_notification。 它通過Intent-Filter注冊在清單中。
manifest.xml
...
<receiver android:name=".MyBroadcastReceiver" >
<intent-filter>
<action android:name="de.tuberlin.snet.gcm.notification" />
</intent-filter>
</receiver>
...
您可以使用LocalBroadcasts
代替普通廣播。 它們本質上就像真實的廣播,但僅對一個應用程序可見。 我假設您想從Service
與應用進行通信? 然后, LocalBroadcasts
應該正是您要尋找的東西,但是在不確切知道如何實現任何事情的情況下,我無法為您提供非常具體的建議。
無論如何,如果您想使用LocalBroadcasts
,則首先必須創建一個BroadcastReceiver
就像使用普通廣播一樣:
private static final String SOME_ACTION = "someAction";
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(SOME_ACTION.equals(action)) {
// Do your work
}
}
};
然后,您可以像這樣注冊和取消注冊BroadcastReceiver
:
@Override
public void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getActivity());
manager.registerReceiver(broadcastReceiver, intentFilter);
}
@Override
public void onPause() {
super.onPause();
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getActivity());
manager.unregisterReceiver(broadcastReceiver);
}
最后,您可以從Service
或應用程序中的其他任何地方發送廣播,如下所示:
Intent intent = new Intent(SOME_ACTION);
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getActivity());
manager.sendBroadcast(intent);
在Android中執行此操作的正確方法取決於您的“庫”的安裝方式。
如果您的庫本身是作為單獨的“應用程序”安裝的,則解決方案是對不同的廣播使用不同的意圖過濾器。 這樣,Android只會將廣播發送給那些已經宣傳了自己興趣的應用。 您需要使用不同的Intent過濾器更新客戶端應用程序,並更改庫以將適當的客戶端使用Intent過濾器作為其廣播的一部分。
如果您的庫與兩個客戶端捆綁在一起,則采用LocalBroadcastManager方法是可以采取的途徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.