Reputation: 1649
i am working on a tutorial on service in this ..i was able to make it run perfectly what i did try is to start service on Oncreate
and it did and make it stop on back button but unfortunately onstop
does not work because it is not showing toast and log here is my code..what causes onstop
not to work
public void onBackPressed() {
AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Confirm Close");
builder.setMessage("Are you sure you want to exit?");
builder.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
stopService(new Intent(this, MyService.class));
System.exit(0);
finish();
android.os.Process.killProcess(android.os.Process.myPid());
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertdialog=builder.create();
alertdialog.show();
}
service code
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service{
private static final String TAG = "MyService";
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
@Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
//Note: You can start a new thread and use it for long background processing from here.
}
@Override
public void onDestroy() {
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
}
Upvotes: 0
Views: 529
Reputation: 6444
Replace your code by following code
public void onBackPressed() {
AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Confirm Close");
builder.setMessage("Are you sure you want to exit?");
builder.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
stopService(new Intent(this, MyService.class));
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertdialog=builder.create();
alertdialog.show();
}
Upvotes: 1