がOK説明されている意図サービスを作成し、これは非常にハックソリューションであり、非常にOOPのようではないが、それは私がやってしまったものですので、誰もがこれまでに見つかった場合、私はここでそれを入れていますシンプルで、あまりエレガントではない(しかし働いている)ソリューションのニーズ。
私はサービスとアプリケーションの間で通信するためにsendBroadcast
とbroadcastReceiver
を使用しています。 問題は何らかの理由でプロセスを送信するとすべてのエキストラが削除されるため、代わりにSharedPrefences
を使用しました。
これは、このような文字列メッセージを発行して購読するために使用する(シングルトン)クラスです。
ビジターインタフェース
public interface Visitor<T> {
public void visit(T element);
}
公開加入者インターフェース:
public interface IPulishSubscribe {
/**
* Publish a new string message
*
* @param key The key to publish under
* @param text The message's content
*/
public void publish(String key, String text);
/**
* Subscribe to a message
*
* @param key The key to subscribe to
* @param visitor The visitor to handle the message when received
*/
public void subscribe(final String key, final Visitor<String> visitor);
}
実装
public class PublishSubscriber implements IPulishSubscribe {
private static IPulishSubscribe _instance = new PublishSubscriber();
private static Context _context;
// key -> handler, isn't of much use ATM, but you may need it for removals...
private Map<String, BroadcastReceiver> _subscribers = new HashMap<String, BroadcastReceiver>();
private PublishSubscriber() {
}
public static void init(Context context) {
_context = context;
}
public static IPulishSubscribe getInstance() {
return _instance;
}
@Override
public synchronized void publish(String key, String text) {
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(_context);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(key, text);
editor.commit();
_context.sendBroadcast(new Intent(key));
}
@Override
public synchronized void subscribe(final String key, final Visitor<String> visitor) {
BroadcastReceiver newSubscriber = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(_context);
String data = mPrefs.getString(key, null);
if (visitor != null) {
visitor.visit(data);
}
}
};
_context.registerReceiver(newSubscriber, new IntentFilter(key));
_subscribers.put(key, newSubscriber);
}
}
出典
2012-03-09 12:38:38
Gal