我在viewpager中包含多个片段,我希望每个片段在点击viewpager中定义的按钮时执行某些操作。我如何向每个片段发送服务,触发每个片段做什么?这是我到目前为止所做的,但它似乎并没有起作用。我从未处理过android中的后台任务,所以我对如何使用它们的知识几乎没有。
viewpager中的代码
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;
}
答案 0 :(得分:1)
在这种情况下,使用应该使用IntentService。 IntentService在第一次调用startService时启动,在进一步调用start service时,intent会依次传递给onHandleIntent()中正在运行的服务实例。示例:http://sohailaziz05.blogspot.com/2012/05/intentservice-providing-data-back-to.html