Activity closes when service is stopped The code which i am using to start service is
Intent intent2 = new Intent(getApplicationContext(), TService.class);
startService(intent2);
and the code to stop service is
Intent intent2 = new Intent(getApplicationContext(), TService.class);
stopService(intent2);
i tried an alternative to use bind service but it showed the same behavior by closing the activity
code to start bind service was
Intent intent2 = new Intent(getApplicationContext(), TService.class);
bindService(intent2, mServerConn, Context.BIND_AUTO_CREATE);
startService(intent2);
& code to stop bind service was
stopService(new Intent(getApplicationContext(), TService.class));
unbindService(mServerConn);
My service TService.class
public class TService extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onDestroy() {
Log.d("service", "destroy");
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("TAG", "service started");
context = getApplicationContext();
return START_NOT_STICKY;
}
}
My Activity MyActivity.java
public class MyActivity extends Activity{
Button start,stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start=(Button) findViewById(R.id.start);
stop=(Button) findViewById(R.id.stop);
final ServiceConnection mServerConn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d("LOG_TAG", "onServiceDisconnected");
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
Log.d("LOG_TAG", "onServiceConnected");
}
};
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent2 = new Intent(getApplicationContext(), TService.class);
intent2.putExtra("value", "1");
startService(intent2);
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent2 = new Intent(getApplicationContext(), TService.class);
intent2.putExtra("value", "2");
stopService(intent2);
}
});
}
private int getClicks() {
clickCount++;
return clickCount % 2 == 0 ? R.drawable.start : R.drawable.stop;
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (TService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
@Override
protected void onPause() {
}
}
I am really stuck on it ,any suggestion or solution will be accepted Thanks in advance