I am trying to run a service in the background. What my app does is when user checks checkbox then service starts and when it is unchecked service is stopped. Which is working perfectly fine. But the problem is when I closed the app from task manager it then also stops the service. What I want is to keep the service running even after it is close from task manager. Then only way to stop that service is by user himself by unckecking the box.
How can I achieve this?
Here is my code
My main activity
public class SampleServiceActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final CheckBox cb = (CheckBox) findViewById(R.id.checkBox1);
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked) {
Toast.makeText(getBaseContext(), "Checked", Toast.LENGTH_LONG).show();
startService(new Intent(getBaseContext(), MyService.class));
} else {
Toast.makeText(getBaseContext(), "Unchecked", Toast.LENGTH_LONG).show();
stopService(new Intent(getBaseContext(), MyService.class));
}
}
});
}
}
My service class
public class MyService extends Service {
Notify n = new Notify();
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
n.initNotification(getBaseContext(), true);
return START_STICKY;
}
//method to stop service
public void onDestroy() {
super.onDestroy();
n.cancelNotification(getBaseContext());
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
}
Update
How can we make this service so that it runs like gtalk service?