2

PollFragment.java通話できる私の中でnew PollTask((MainActivity)getActivity()).execute((Void)null);

そして私の中でPollTask.java

public PollTask(MainActivity activity){
        super(activity);
        TerminalCfg terminalCfg = Global.getTerminalCfg();
        terminalId = terminalCfg.getTerminalId();
        retailerAcc = terminalCfg.getRetailerAcc();
        internalId = APIUtil.getInternalId(activity);
        username = APIUtil.getUsername(activity);
    }

そして今、私は以下のように extendsnew PollTask((MainActivity)getActivity()).execute((Void)null); で inを呼び出したいです :MyBackgroundServiceService

public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
        new PollTask((MainActivity)getActivity()).execute((Void)null);
        // For each start request, send a message to start a job and deliver the
        // start ID so we know which request we're stopping when we finish the job
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        mServiceHandler.sendMessage(msg);

        // If we get killed, after returning from here, restart
        return START_STICKY;
    }

getActivity()メソッドを呼び出すために を置き換える他の方法はありますか?

4

1 に答える 1

2

AServiceは とは別のコンポーネントであるActivityため、 を使用して A への参照を取得することはできませんgetActivity()。サービスは、UI スレッドとは別のスレッドでのバックグラウンド作業を含む (ただしこれに限定されません)、ユーザーには見えない作業を行うように設計されています。サービスはより堅牢になり、ユーザーには見えない実行中の作業をより詳細に制御できます。を実行する必要はありませんActivity

は、UI スレッドとは別の の内部から作業AsyncTaskを行う簡単な方法です。ActivityThread

AsyncTask基本的に、は必要ありませんService

代わりに、 をService生成するか、ワーカーの作成を処理する をThread使用する必要があります。次に、終了したら、インテントを開始するか、IntentServiceThreadActivityLocalBroadcast

または、 を に関連付けて、とがインターフェースを介して相互に直接呼び出すことができるメソッドを提供することもServiceできます。これらはバインドされたサービスと呼ばれ、が存続している間だけ存続します。ActivityServiceActivityIBinderActivity

IntentService を試す

あなたの最善の策は、IntentService

http://developer.android.com/reference/android/app/IntentService.html

于 2013-11-14T04:49:26.817 に答える