2013-04-30 11 views
6

複数のアクティビティで使用/バインドされているサービスがあります(onPause/onResume内で別のバインドが行われる前に、1つのアクティビティがバインド解除されるように注意して書きました)。しかし、私はくっつかないサービスでメンバー....Androidサービスがシングルトンとして機能していません

活動1気づい:

private void bindService() { 
    // Bind to QueueService 
    Intent queueIntent = new Intent(this, QueueService.class); 
    bindService(queueIntent, mConnection, Context.BIND_AUTO_CREATE); 
} 

... 

bindService(); 

... 

mService.addItems(downloads);  // the initial test adds 16 of them 

活動を2:

bindService();        // a different one than activity 1 
int dlSize = mService.getQueue().size(); // always returns 0 (wrong) 

サービスのコード:

public class QueueService extends Service { 
    private ArrayList<DownloadItem> downloadItems = new ArrayList<DownloadItem(); 

    // omitted binders, constructor, etc 

    public ArrayList<DownloadItem> addItems(ArrayList<DownloadItem> itemsToAdd) { 
     downloadItems.addAll(itemsToAdd); 
     return downloadItems; 
    } 

    public ArrayList<DownloadItem> getQueue() { 
     return downloadItems; 
    } 
} 

サービスを変更すると、サービスのdownloadItems変数が静的変数に変わります。すべてが完全に機能します。しかし、それをしなければならないことは私を心配します。私は前にこのようにシングルトンを使ったことはありません。これは、これらのいずれかを使用する正しい方法ですか?

+1

あなたのアクティビティのどこでもstartService()を呼び出していますか?これにより、サービスはシングルトンとして生き続けることができます。さもなければそれに縛られる活動が破壊されるときそれは破壊されるでしょう。 – Nospherus

+0

@Nospherus私はまもなく行ったことを追加します - dr; "bindService"は "startService()"と同様に動作しますか? –

+3

いいえ、startService()とbindService()の両方を呼び出す必要があります。 bindService()だけを呼び出すと、バインド解除するとすぐにサービスが終了します。 startService()を呼び出すと、サービス内でstopService()(またはstopSelf())を呼び出すまで有効になります。 @Nospherusありがとうございます; – Nospherus

答えて

7

Nospherusが正しいことが判明しました。私がしなければならなかったのは、私のbindService()の横にあるstartService()コールでした。

複数のstartService()コールがコンストラクタを何度も呼び出さないので、それらは私が必要としていたものです。 (これは私の一部に非常に怠惰であるが、それは今のために働く私が始めた(とないバインド)サービスのために確認する方法がわからないと思います。)私のコードは次のようになります。

Intent queueIntent = new Intent(getApplicationContext(), QueueService.class); 
bindService(queueIntent, mConnection, Context.BIND_AUTO_CREATE); 
startService(queueIntent); 

も参照してくださいBind service to activity in Android

+0

woow、私は私の午前中にサービスの2つのインスタンスの解決策を探して失った、ここには...ちょうどstartServiceです。 – rcorbellini

+0

私はそれにバインドする前に、より良い習慣をstartServiceだろう。 – benchuk

関連する問題