3

I'm implementing running the service in background and service will be stop and start click on toggle button.Service is start in 1st activity and stop the service in another activity when click on toggle button.When i run the application service is automatically start in 1st activity which i start in onCreate() method in 1st activity and another activity toggle button status is already on status but when i toggle button is going to off service stop but when i back to 1st activity service is again start.Please can any one help me.Here is my code

public class MyService extends Service
{
    private static final String TAG = "MyService";
    MediaPlayer player;
    private final String StrMyService="myservice";



    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onCreate");

        player = MediaPlayer.create(this, R.raw.braincandy);
        player.setLooping(false); // Set looping
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");
        player.stop();
    }

    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");
        player.start();
    }
}




public class Service_Demo extends Activity implements OnClickListener 
{
      private static final String TAG = "ServicesDemo";


      @Override
      public void onCreate(Bundle savedInstanceState)
      {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        System.out.println("In OnCreate(");
        startService(new Intent(this, MyService.class));


      }
}


public class Toggle_Activity extends Activity
{
    ToggleButton tgButton;
    private boolean isService=false;
    private String strService;
    public final String service_Prefs="servicePrefs";
    private static final String StrMyService = "zdf";


    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.toggle);

        final SharedPreferences servicePrefs=this.getSharedPreferences("Service_Prefs",MODE_WORLD_READABLE);
        strService=servicePrefs.getString(StrMyService , "myservice");
        Log.e("",""+strService);

        final boolean mBool = servicePrefs.getBoolean("myservice", true);
        Log.e("Boolean Value mBool","="+mBool);
        Boolean b = mBool;
        Log.e("Update pref", b.toString());

        tgButton = (ToggleButton)findViewById(R.id.toggleButton);
        tgButton.setChecked(mBool);




        final boolean mBool1 = servicePrefs.getBoolean("myservice", false);
            final Boolean c = mBool1;
        Log.e("Update pref", c.toString());


        tgButton=(ToggleButton)findViewById(R.id.toggleButton);
        tgButton.setOnClickListener(new OnClickListener()

      {

            @Override
            public void onClick(View v) 
                  {
                // TODO Auto-generated method stub

                if(tgButton.isChecked())
                {
                    startService(new Intent(Toggle_Activity.this , MyService.class));
                    System.out.println("Service is started in togglr button");

                }
                else
                {   

                    stopService(new Intent(Toggle_Activity.this,MyService.class));
                    System.out.println("Service is stopped in togglr button");

                }
            }
        });


    }

}
Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137
TJM
  • 117
  • 1
  • 3
  • 14

2 Answers2

0

in the first activity, you'd put startService(new Intent(this, MyService.class)) in onresume from oncreate

minjie
  • 79
  • 2
0

I figured this out the best way possible. I basically linked my toggle button and my service together using a shared preference and listeners. I called this shared preference "service_running" and then implemented my listeners in the activity onCreate() method the toggle button is present in (in this case, MainActivity.

In my onCreate() heres what I did:

    // set toggle button based on service running
    final ToggleButton toggle = (ToggleButton)findViewById(R.id.toggleButton);
    toggle.setChecked(serviceRunning(SendService.class));
    toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged (CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                startSendService();
            }
            else {
                stopSendService();
            }
        }
    });

    // set shared pref listener for toggle
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.OnSharedPreferenceChangeListener myPrefListner = new SharedPreferences.OnSharedPreferenceChangeListener(){
        public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
            if (key.equals("service_running")) {
                toggle.setChecked(prefs.getBoolean("service_running", false));
            }
        }
    };
    prefs.registerOnSharedPreferenceChangeListener(myPrefListner);

startSendService() and stopSendService() simply start or stop my service depending on if it is running and has the correct app permissions or not.

Heres the method which checks if a service is running (credit to @geekQ in this thread):

private boolean serviceRunning (Class<?> serviceClass) {
    // check if a service class is currently running
    ActivityManager manager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);

    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }

    return false;
}

And then in my service, in the onStartCommand() I just changed the shared preference to true, and in the onDestroy() I changed it to false.

The only caveat with this is that you have to hide this shared preference from your preference screen, which can be done with:

getPreferenceScreen().removePreference(findPreference("service_running"));
Community
  • 1
  • 1
kjdion84
  • 9,552
  • 8
  • 60
  • 87