0

我在 viewpager 中包含多个片段,我希望每个片段在单击 viewpager 中定义的按钮时执行某些操作。我如何向这些片段中的每一个发送服务,触发每个片段做某事?这是我到目前为止所拥有的,但它似乎不起作用。我从来没有处理过android中的后台任务,所以我对如何使用它们的知识几乎没有。

浏览器中的代码

public boolean onOptionsItemSelected(android.view.MenuItem item) {
    switch (item.getItemId()) {
        case R.id.apply:

        Intent in = new Intent(this, Friday.class);
        in.putExtra("isClicked", "clicked");
        startService(in);

        Intent inte = new Intent(this, Thursday.class);
        inte.putExtra("isClicked", "clicked");
        startService(inte);

        Intent inten = new Intent(this, Wednesday.class);
        inten.putExtra("isClicked", "clicked");
        startService(inten);

        Intent intent = new Intent(this, Tuesday.class);
        intent.putExtra("isClicked", "clicked");
        startService(intent);

        Intent intents = new Intent(this, Monday.class);
        intents.putExtra("isClicked", "clicked");
        startService(intents);
    }

    return true;
}

片段中的代码

public int onStartCommand(Intent intent, int flags, int startId) {
    SharedPreferences sharedPref = getActivity().getSharedPreferences("schedule",Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString("g_Friday", editGBand.getText().toString() );
    editor.putString("b_Friday", editCBand.getText().toString() );
    editor.putString("adv1_Friday", editADV1Band.getText().toString() );
    editor.putString("adv2_Friday", editADV2Band.getText().toString() );
    editor.putString("c_Friday", editCBand.getText().toString() );
    editor.putString("f_Friday", editFBand.getText().toString() );
    editor.apply();

    Intent i = new Intent(getActivity(), MainActivity.class);
    startActivity(i);

    return Service.START_NOT_STICKY;

}
4

1 回答 1

1

在这种情况下使用应该使用 IntentService。IntentService 在第一次调用 startService 时启动,并在进一步调用 start service 时启动,intent 依次传递给 onHandleIntent() 中正在运行的服务实例。示例:http ://sohailaziz05.blogspot.com/2012/05/intentservice-providing-data-back-to.html

于 2014-06-05T18:07:26.820 回答