Search code examples
androidandroid-fragmentsonclickandroid-serviceonstart

How to send a service to multiple fragments from a button click


I have multiple fragments contained in a viewpager, and I would like each fragment to do something when a button defined in the viewpager is clicked. How would I send a service to each of these fragments, triggering each fragment to do something? Here is what I have so far, but it doesn't seem to be working. I've never dealt with background tasks in android, so my knowledge of how to use them is pretty much next to none.

code in the 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;
}

code in the fragments

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;

}

Solution

  • Use should use IntentService in this case. IntentService is started on first call of startService and on further calls to start service, intent is passed to the running instance of service in onHandleIntent() sequentially. Example: http://sohailaziz05.blogspot.com/2012/05/intentservice-providing-data-back-to.html