I write this code in the onDestroy() method.
#Override
public void onDestroy()
{
MessageService.this.stopSelf();
messageThread.isRunning = false;
System.exit(0);
super.onDestroy();
}
And close the service in other Activity.
stopService(new Intent(MainOptionActivity.this,MessageService.class));
I tried many code, it can not close the service when close the background. Could anyone give me some advice? Thanks.
Here is a simple code for service class
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(getApplicationContext(), "MSG onCreate SERVICE", Toast.LENGTH_LONG).show();
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "MSG onStartCommand SERVICE", Toast.LENGTH_LONG).show();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
Toast.makeText(getApplicationContext(), "MSG STOP SERVICE", Toast.LENGTH_LONG).show();
super.onDestroy();
}
}
and here is the code for testing this service
startService(new Intent(this, MyService.class));
new Timer().schedule(new TimerTask() {
#Override
public void run() {
startService(new Intent(getApplicationContext(), MyService.class));
}
}, 5000);
new Timer().schedule(new TimerTask() {
#Override
public void run() {
stopService(new Intent(getApplicationContext(), MyService.class));
}
}, 10000);
this is working just fine. Also add this code in manifest
<service android:name=".MyService" />
Don't use System.exit(0) on Android, instead use finish (in Activity for example).
But there is no need to stop itself onDestroy method, it is actually gonna be stopped and destroyed (that's what onDestroy method is for).
You stop the execution of the method with System.exit(0); and therefore system never reaches super.onDestroy(); point and service is not destroyed.
Try just
#Override
public void onDestroy() {
messageThread.isRunning = false;
super.onDestroy();
}
Related
So I have code that I want called when my application is closed. Not just when it is sent to the background or the surface is destroyed. How do I do this? Is there a method that I can override in a SurfaceView or Activity class?
New Edit - current BackgroundService class:
public class BackgroundService extends Service {
private String savedString;
public void onCreate() {
System.out.println("Service created");
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("start command: ");
savedString = intent.getStringExtra("myString);
return super.onStartCommand(intent, flags, startId);
}
public IBinder onBind(Intent intent) {
return null;
}
public void onTaskRemoved(Intent rootIntent) {
System.out.println("the saved string was: " + savedString);
super.onTaskRemoved(rootIntent);
}
public void onDestroy() {
System.out.println("destroyed service");
super.onDestroy();
}
}
Where I then have this in my other class:
Intent serviceIntent = new Intent(activity.getApplicationContext(), BackgroundService.class);
serviceIntent.putExtra("myString", "this is my saved string");
activity.startService(serviceIntent);
you need to add a background service
public class BackgroundServices extends Service
{
#Override
public void onCreate() {
Toast.makeText(this, "start", Toast.LENGTH_SHORT).show();
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
then in your activity. where you want to trigger this service
use
startService(new Intent(getBaseContext(), BackgroundServices.class));
in your case it will be call on onDestory function of that activity
Yes when the process is terminated
That is not possible in general. Nothing in your app is called when the process is terminated.
For example when you open the running apps screen, and swipe away the app to stop it from running
That is a task removal. It may result in your process being terminated, and there are many ways in which your process can be terminated that has nothing to do with task removal.
To detect task removal, override onTaskRemoved() in a Service.
I have an alarm broadcast receiver where I want to check if my app is completely closed, which means app is neither running in foreground nor background.
Can anyone tells me how can I check this ?
You can create a service and overwrite the onTaskRemoved() method
From the Documentation
the user has removed a task means swiping the app out from the task
list. Stopping the Service from the phone's settings does not trigger
Service.onTaskRemoved().
Code:
public class AppStopped extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("Service", "Service Started");
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("Service", "Service Destroyed");
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.e("Service", "END");
Toast.makeText(getApplicationContext(), "App Stopped", Toast.LENGTH_SHORT).show();
//Code here
stopSelf();
}
}
In Manifest:
<service android:name="com.example.AppStopped"
android:stopWithTask="false" />
Start the service in your activity like:
startService(new Intent(getBaseContext(), AppStopped.class));
In your Application class:
public class MyApplication extends Application {
#Override
public void onTerminate() {
super.onTerminate();
// your app is closed
}
}
For a demo I print a Toast after Evert 10 sec. using Service class.
It works fine, I'm getting the Toast after every 10 sec if I am on the Activity when I leave the app, Service is not giving the o/p.
But I want to that toast either I'll kill the App or back press Here is code snippet :
ServiceDemo.java
public class ServiceDemo extends Activity {
private Handler myHandler = new Handler();
private Runnable drawRunnable = new Runnable() {
#Override
public void run() {
as();
myHandler.postDelayed(this, 10000);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service_demo);
myHandler.postDelayed(drawRunnable, 10000);
startService(new Intent(this, MyService.class));
}
public void as(){
startService(new Intent(this, MyService.class));
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
Service.java
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "HOHO Service Created...", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service Started...", Toast.LENGTH_LONG).show();
}
}
Edit 1
moveTaskToBack(true);
I put this into the onBackPressed method I Service give the o/p if I am not on the screen but When I kill the App, Service not responding
I think you need to override onStartCommand instead of onStart()
like:
public int onStartCommand(Intent intent, int flags, int startid)
{
Toast.makeText(this, "Service Started...", Toast.LENGTH_LONG).show();
return Service.START_STICKY;
}
i think AlarmManager is what you want.
You have to user AlarmManager, here's an example : Alarm Manager Example
Your task will be executed even if the application is terminated.
But if the application is killed by the user, the Alarm will be canceled. See this discussion How to create a persistent AlarmManager
I'm following the book 'Beginning Android 4 Development', and I'm controlling a service using the following functions from buttons:
public void startService(View view) {
startService(new Intent(getBaseContext(), QOLService.class));
}
public void stopService(View view) {
stopService(new Intent(getBaseContext(), QOLService.class));
}
QOLService.java includes
public class QOLService extends Service {
int counter = 0;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Keep running service until stopped, so return sticky
Timer timer=new Timer();
TimerTask tt =new TimerTask() {
#Override
public void run() {
Log.d("QOLService", String.valueOf(++counter));
}
};
timer.scheduleAtFixedRate(tt, 0, 1000);
Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed", Toast.LENGTH_LONG).show();
}
As intended, on pressing the start button I get the 'service started' toast, and in logcat I get a message incrementing every second. This continues, as intended, even when the application is closed.
When I click the stopservice button, I also get the expected 'service destroyed' message, but the timer lives on! If I close the application it still keeps going. If I click the stopservice button again, it does NOT given the service destroyed message, as if it had been successfully destroyed the first time.
Am I calling my timer inappropriately? If so, I seem to be doing it exactly as the book advises!
Am I calling my timer inappropriately?
You are never stopping the timer. Hence, it will keep running until the process is terminated. You should stop the timer in onDestroy().
I am agree with CommonsWare, You haven't stop your timer in the code. I suggest you to go this way,
public class QOLService extends Service {
int counter = 0;
Timer timer;
TimerTask tt;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Keep running service until stopped, so return sticky
timer=new Timer();
tt =new TimerTask() {
#Override
public void run() {
Log.d("QOLService", String.valueOf(++counter));
}
};
timer.scheduleAtFixedRate(tt, 0, 1000);
Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed", Toast.LENGTH_LONG).show();
tt.cancel();
timer.cancel();
}
}
The cancel() method will stop your Timer as well as.
It might be because the system is trying to restart your service because you are returning START_STICKY from onStartCommand. Try returning START_NOT_STICKY instead.
Hi friends i have a one problem to solve...I want to destroy the service completely, once i call onDestroy() method from Activity. But my problem is that i am unable to destroy it completely.. in background its keep on running, i am sharing the sample code what i tried..
//Activity Class
public class ServiceToAct extends Activity {
private static final String TAG = "BroadcastEvent";
private Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
intent = new Intent(this, BroadcastService.class);
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(myService.BROADCAST_ACTION));
}
/*#Override
protected void onResume() {
super.onResume();
}*/
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
#Override
protected void onDestroy() {
stopService(intent);
Toast.makeText(this, "Destroy Completely", Toast.LENGTH_LONG).show();
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
}
// service class
public class myService extends Service {
private static final String TAG = "BroadcastEvent";
public static final String BROADCAST_ACTION = "com.service.activity.myService";
private final Handler handler = new Handler();
Intent intent;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "created", Toast.LENGTH_LONG).show();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "start", Toast.LENGTH_LONG).show();
handler.removeCallbacks(sendToUI);
handler.postDelayed(sendToUI, 1000);
}
#Override
public void onDestroy() {
super.onDestroy();
stopSelf();
//stopService(intent);
Toast.makeText(this, "Destroy", Toast.LENGTH_LONG).show();
}
private Runnable sendToUI = new Runnable() {
#Override
public void run() {
myData();
handler.postDelayed(this, 10000);
}
};
private void myData() {
Log.d(TAG, "keep on entering");
Toast.makeText(this, "Keep on despling in UI", Toast.LENGTH_LONG).show();
sendBroadcast(intent);
}
}
Here Actually i want to update my UI from service, Mine everything is working, but if i destroy the service its keep on calling myData() method, and i am getting the Toast msg if i close the application also.
My issue is i don't want that toast msg once the service is desroyed
I used stopService(intent) method, which destroy the service, but background method myData() is keep on calling
for stop service completely use this ..
myActivity.java
#Override
public void onDestroy() {
stopService(intent);
super.onDestroy();
Toast.makeText(this, "Destroy", Toast.LENGTH_LONG).show();
}
service.java
#Override
public void onDestroy()
{
stopSelf();
super.onDestroy();
}
You'd better never call onXxx() derectly.
Use stopService(Intent i) in your activity and stopSelf() in you service to stop instead.
use stopService() method after updating UI
or
Instead of using startService use bindService in the activity. When activity destroys, service also destroys