2012-03-07 3 views
0

私はthisチュートリアルを使用して、アプリケーション自体がバックグラウンドになっていても常にバックグラウンドで実行されるサービスを使いやすくしています私のメインプロセスとサービスの間の文字列。 事は、文字列のマーシャリングが非常に簡単であると考えられていますが、より複雑なものについては、AIDLが必要です。 私は文字列のみメッセージを送信したいので、私はこれを行うには非常に簡単な方法がなければならない考え出したが、私はそれを見つけることができません。..アンドロイドは別のプロセスで実行されているサービスに文字列を送信します

おかげ

答えて

0

がOK説明されている意図サービスを作成し、これは非常にハックソリューションであり、非常にOOPのようではないが、それは私がやってしまったものですので、誰もがこれまでに見つかった場合、私はここでそれを入れていますシンプルで、あまりエレガントではない(しかし働いている)ソリューションのニーズ。

私はサービスとアプリケーションの間で通信するためにsendBroadcastbroadcastReceiverを使用しています。 問題は何らかの理由でプロセスを送信するとすべてのエキストラが削除されるため、代わりに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); 
    } 
} 
0

私は意図サービスがへの道であると仮定行く。 ハウツーhere

関連する問題