Seth
Seth

Reputation: 1835

how to keep a service alive without an ongoing notification

I know i can use an ongoing notification to keep my service alive but i have a service that is holding a broadcast receiver. I do not want to use a notification to simply hold my broadcast receiver. I know also i can register my receiver inside my app's manifest but i want the user to be able to control if the receiver is active or not.

Here is the service that keeps restarting.

public class DockServiceListener extends Service{

IntentFilter filter;
BroadcastReceiver mReceiver;

public void onCreate() {
    super.onCreate();

    Toast.makeText(getApplicationContext(), "Receiver started!", Toast.LENGTH_SHOR

    filter = new IntentFilter(Intent.ACTION_DOCK_EVENT);
    mReceiver = new DockReceiver();

}

public int onStartCommand(Intent intent, int flags, int id) {
    super.onStartCommand(intent, START_STICKY, id);

    registerReceiver(mReceiver, filter);

    return id;
}

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

Very simple. I also know it may be android cleaning up but how come Facebook messenger and other service's arent being closed? Unless i just dont know it cause it doesnt have the toast message? Or is there a way to only run onCreate once?

Well anyhow, thanks everyone for looking! Hopefully someone can better educate me! :)

EDIT: New method wondering if this is right?

startBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            PackageManager pm = getApplicationContext().getPackageManager();
            ComponentName dockReceiver = new ComponentName(getApplicationContext(), DockReceiver.class);
            pm.setComponentEnabledSetting(dockReceiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0);
            finish();



        }
    });

    stopBtn.setOnClickListener(new View.OnClickListener() {

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

            PackageManager pm = getApplicationContext().getPackageManager();
            ComponentName dockReceiver = new ComponentName(getApplicationContext(), DockReceiver.class);
            pm.setComponentEnabledSetting(dockReceiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0);
            finish();

        }
    });

Upvotes: 0

Views: 583

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006584

I know also i can register my receiver inside my app's manifest but i want the user to be able to control if the receiver is active or not.

Then use PackageManager and setComponentEnabledSetting() to enable or disable your BroadcastReceiver that is registered in the manifest. You not need to waste the user's RAM with a service just to control whether "the receiver is active or not".

Upvotes: 1

Related Questions