Search code examples
androidservicebroadcastreceiver

Adding a service and removing it under next condition


I need to start a service and end it under some condition. I previously used IntentService which I found to be incorrect for the purpose(if I am right). I have started using service with BroadcastReciever. But still can't get the desired result. I may elaborate or even paste my code if needed. But for now, I just need something like a flow chart or pseudocode. The condition would be checked from Preference settings. If checked, I would like to run the service in background else stop the service. Please, can any one out here help me.

EDITED:

My MainActivity:

public class MainActivity extends ListActivity {
    private LocalWorldService s;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = new Intent(this, LocalWorldService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unbindService(mConnection);
    }

    private ServiceConnection mConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName className, IBinder binder) {
            LocalWorldService.MyBinder b = (LocalWorldService.MyBinder) binder;
            s = b.getService();
            Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_SHORT)
                    .show();
        }

        public void onServiceDisconnected(ComponentName className) {
            s = null;
            Toast.makeText(MainActivity.this, "Disconnected", Toast.LENGTH_SHORT)
            .show();
        }
    };

My Service:

public class LocalWorldService extends Service {

    private final IBinder mBinder = new MyBinder();
    private ArrayList<String> list = new ArrayList<String>();

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        Toast.makeText(getApplicationContext(), "Magnet is on", Toast.LENGTH_LONG).show();
        return Service.START_NOT_STICKY;
    }

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

    public class MyBinder extends Binder{
        LocalWorldService getService(){
            return LocalWorldService.this;
        }
    }

    public List<String> getWordList(){
        return list;
    }

Following are two class for BroadCastReceiver:

public class MyScheduleReceiver extends BroadcastReceiver{

    private static final long REPEAT_TIME = 15 * 1000;
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, MyStartServiceReceiver.class);
        PendingIntent pending = PendingIntent.getBroadcast( context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, 15);
        service.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), REPEAT_TIME, pending);
    }

And:

public class MyStartServiceReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Intent service = new Intent(context, LocalWorldService.class);
        SharedPreferences pref = PreferenceManager
                .getDefaultSharedPreferences(context);
        Map<String, ?> x = pref.getAll();
        boolean momoMagnetIsOn = (Boolean) x.get("key_momo_magnet");
        if (momoMagnetIsOn){
            context.startService(service);
        }
        else{
            context.stopService(service);
        }
    }

CORRECTION: I need to override onDestroy().


Solution

  • override onDestroy method in Service When ever you want to start a service all you need is

     startService(new Intent(this, MainService.class));
    

    And to Stop a service anytime just call

    stopService(new Intent(this, MainService.class));
    

    Remember service needs to be declared in AndroidManifest.xml. As you said that your service is working. I'm sure you have done that. Still AndroidManifest.xml

     <service android:enabled="true" android:name=".MainService" />