Stopping infinite service? - android

I am making an app which consists of an infinite running service which needs to be stopped when the checkbox is disabled.
i am currently inheriting intentservice class for Myservice class but the problem is it doesn't gets stopped on clicking the buttons(which calls stopservice) and keeps running, i have tried logging and ondestroy() does gets called but service doesn't stop.
i have Also tried inheriting service class but still same. i am posting the code below.
From MainActivity:`service.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Intent intent= new Intent(MainActivity.this,Myservice.class);
if(sp==false)
{ Log.d("service1", "Startservice invoked");
startService(intent);
sp=true;
}
else if(sp==true)
{
Log.d("service1", "Stopservice invoked");
stopService(intent);
sp=false;
}
return false;
}
});`
sp is just a static flag to check whether the checkbox was clicked with initial value as false.(isenabled() method was giving problems)
Myservice code:
public class Myservice extends IntentService {
public Myservice() {
super("My Service");
}
#Override
protected void onHandleIntent(Intent intent) {
while(true){
Log.d("service1", "Service is running");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}}
I know why all this is happening(onhandleintent runs on a seperate thread). But is there any way to stop the infinite thread/loop on preference change?

Related

How Android O affect background service to reduce battery drain?

I create a service that start a new thread to do stuff. In Android O, the android document said if the service is not a foreground service, then it will be stopped by the system. But I tested the following code, the service is destroyed but the thread is still running.
My question is how the system can save user's battery if the thread is allowed to be run even if the service is stopped?
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startService(View view) {
Intent intent = new Intent(this, MyService.class);
startService(intent);
}
public void stopService(View view) {
stopService(new Intent(this, MyService.class));
}
}
MyService
public class MyService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("run in service: ");
}
}
}).start();
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
System.out.println("service onDestroy");
}
}
Did you test this behaviour for longer hours ? I had the same set-up with a service (started via main thread) running a worker thread inside. Upon testing the set-up for longer duration like 2-3 days. You will notice that system shuts down the entire process. So you can not rely on doing the background execution with a worker thread. Better approach is to use periodic or timed Jobs.

Service Automatic Called on Destroying Activity

I am stuck with the problem of Activity + Service in that I have following number of Activities and Services.
Activities:
LoginActivity => OrderListActivity => AddOrderActivity => ConfirmOrderActivity
Services:
ReceivingOrderService - Receiving New Data From Server
SendingOrderService - Sending new Data to Server
Above both Service Calling from another Separate Service on duration of some interval.
CheckAutoSyncReceivingOrder - To call ReceivingOrderService (Interval 15Mins)
CheckAutoSyncSendingOrder - To call SendingOrderService (Interval 3Mins)
CheckAutoSyncReceivingOrder:
public class CheckAutoSyncReceivingOrder extends Service {
Timer timer;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
if(timer != null) {
timer.cancel();
Log.i(TAG, "RECEIVING OLD TIMER CANCELLED>>>");
}
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if(InternetConnection.checkConnection(getApplicationContext())) {
if(getDatabasePath(DatabaseHelper.DATABASE_NAME).exists())
startService(new Intent(CheckAutoSyncReceivingOrder.this, ReceivingOrderService.class));
} else {
Log.d(TAG, "Connection not available");
}
}
}, 0, 60000); // 1000*60*15 = 9,00,000 = 15 minutes
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(timer != null)
timer.cancel();
Log.d(TAG, "Stopping Receiving...");
}
}
CheckAutoSyncSendingOrder:
public class CheckAutoSyncSendingOrder extends Service {
Timer timer;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
if(timer != null) {
timer.cancel();
Log.i(TAG, "OLD TIMER CANCELLED>>>");
}
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
Log.i(TAG, ">>>>>>>> SENDING AUTO SYNC SERVICE >>>>>>>>");
if(InternetConnection.checkConnection(getApplicationContext())) {
if(getDatabasePath(DatabaseHelper.DATABASE_NAME).exists())
startService(new Intent(CheckAutoSyncSendingOrder.this, SendingOrderService.class));
} else {
Log.d(TAG, "connection not available");
}
}
}, 0, 120000); // 1000*120*15 = 1,800,000 = 15 minutes
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(timer != null)
timer.cancel();
Log.d(TAG, "Stopping Sending...");
}
}
ConfirmOrderActivity#Final Task which i have called for Insert Data:
new AsyncTask<Void, Void, Integer>() {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(
ConfirmOrderProductActivity.this);
progressDialog.setMessage("Inserting "
+ (isInquiry ? "Inquiry" : "Order") + "...");
progressDialog.setCancelable(false);
progressDialog
.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
}
#Override
protected Integer doInBackground(Void... params) {
// TODO Auto-generated method stub
int account_id = context.getSharedPreferences(PREF_DATA,
MODE_APPEND).getInt(DATA_ACCOUNT_ID, 0);
/**
* Check Whether isInquiry or not...
*/
product_type = isWeight ? 1 : 0;
if (isInquiry) {
/*
* INSERTING DATA IN INQUIRY TABLE
*/
return m_inquiry_id;
} else {
/*
* INSERTING DATA IN ORDER TABLE
*/
return m_order_id;
}
}
#Override
protected void onPostExecute(Integer m_order_id) {
// TODO Auto-generated method stub
super.onPostExecute(m_order_id);
progressDialog.dismiss();
if (dbHelper.db.isOpen())
dbHelper.close();
String title = "Retry";
String message = "There is some problem, Go Back and Try Again";
AlertDialog.Builder alert = new AlertDialog.Builder(
ConfirmOrderProductActivity.this);
if (m_order_id != -1) {
title = isInquiry ? "New Inquiry" : "New Order";
message = isInquiry ? "Your Inquiry Send Successfully." : "Your Order Saved Successfully.";
alert.setIcon(R.drawable.success).setCancelable(false);
} else {
alert.setIcon(R.drawable.fail).setCancelable(false);
}
alert.setTitle(title).setMessage(message)
.setPositiveButton("OK", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
startActivity(new Intent(
ConfirmOrderProductActivity.this,
FragmentChangeActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
/* Opening Left to Right Animation */
overridePendingTransition(R.anim.right_out,
R.anim.right_in);
}
});
AlertDialog alertDialog = alert.create();
alertDialog.show();
}
}.execute();
Everything is working fine as per flow of inserting records in database.
After Adding Inquiry:
Destroying Activity and Getting following Logcat:
Main Problem:
When I placed order successfully from ConfirmOrderActivity, It is displaying AlertDialog of Success Message which is cancellable false. When I Stop application from this Activity, Its calling both CheckAutoSyncReceivingOrder and CheckAutoSyncSendingOrder automatically.
Edited:
I am calling both Service from LoginActivity only, after that it
will called automatically after given intervals But Problem occurs
when I destroy ConfirmOrderActivity when dialog is shown.
I didn't know why it happens that Why its running automatically when I stop Activity Directly.
I have tried onStartCommand() with START_NON_STICKY in Service but not working. (as START_STICKY is default.)
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
Is there any solution?
You need to either run your service in the foreground so when the activity is destroyed so will the service or use a bound service and manage the binding with the activity lifecycle, so it is not continually restarted when the activity is destroyed.
From this android docs tutorial Bound Services
You need to do this for each service.
public class CheckAutoSyncReceivingOrder extends Service {
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
CheckAutoSyncReceivingOrder getService() {
return CheckAutoSyncReceivingOrder.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
From your activity that creates and calls the service, that when it is destroyed you want your service destroyed.
public class BindingActivity extends Activity {
CheckAutoSyncReceivingOr mService;
boolean mBound = false;
#Override
protected void onStart() {
super.onStart();
// Bind to CheckAutoSyncReceivingOr
Intent intent = new Intent(this, CheckAutoSyncReceivingOr.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to CheckAutoSyncReceivingOr, cast the IBinder and get CheckAutoSyncReceivingOr instance
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}
And manage the service lifecycle. Restart the same service with your timer, do not create a new service.
public class ExampleService extends Service {
int mStartMode; // indicates how to behave if the service is killed
IBinder mBinder; // interface for clients that bind
boolean mAllowRebind; // indicates whether onRebind should be used
#Override
public void onCreate() {
// The service is being created
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The service is starting, due to a call to startService()
return mStartMode;
}
#Override
public IBinder onBind(Intent intent) {
// A client is binding to the service with bindService()
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
// All clients have unbound with unbindService()
return mAllowRebind;
}
#Override
public void onRebind(Intent intent) {
// A client is binding to the service with bindService(),
// after onUnbind() has already been called
}
#Override
public void onDestroy() {
// The service is no longer used and is being destroyed
}
}
Note START_NOT_STICKY will only prevent the service from restarting if the device is low on memory.
Be mindful that you where you are starting services, just start it once and allow the service to maintain it's own lifecycle until you destroy it with your activity.
This is in reply to your original unedited question, when the app was mysteriously crashing:
You need to destroy the dialog before the context window the dialog is attached to. That will cause a problem. So this is where program flow and the order of closing and cleaning up resources is important. They, frequently have to be destroyed in the reverse order they were created if they are dependent upon parent windows (which is often in the form of a particular activity).
It's difficult to trace your code, so this is a generic answer.
Make use of onPause and onDestroy in your activities.
In all your activities, manage any resources you have created within that activity and with a null check, close them down. Like you have in your service class. If you want to override the parent onDestroy, place your custom code before super.onDestroy.
protected void onDestroy() {
if(timer != null)
timer.cancel();
Log.d(TAG, "Stopping Sending...");
super.onDestroy();
}
(1)For Your Dialog:
The solution is to call dismiss() on the Dialog you created before exiting the Activity, e.g. in onDestroy(). All Windows & Dialog should be closed before leaving an Activity.
(2)For Your service autostart:
you have to look at the value the service returns from its onStartCommand method. The default value is START_STICKY which will restart the service after it is destroyed. Take a look at the onStartCommand documentation for more details:
If the process that runs your service gets killed, the Android system will restart it automatically it is default behavior.
This behavior is defined by the return value of onStartCommand() in your Service implementation. The constant START_NOT_STICKY tells Android not to restart the service if it s running while the process is "killed".
You need to Override method onStartCommand() in your service class and move all your code from onStart() method to onStartCommand() method.
According to the Android Documentation:
For started services, there are two additional major modes of
operation they can decide to run in, depending on the value they
return from onStartCommand(): START_STICKY is used for services that
are explicitly started and stopped as needed, while START_NOT_STICKY
or START_REDELIVER_INTENT are used for services that should only
remain running while processing any commands sent to them
onStart() method calls each time when service is restarted but onStartCommand() method will not called if you return START_NON_STICKY.
Don't use onStart() anymore, it's deprecated.
I hope it helps you.
Services got killed when application got killed (add logs in service onStartCommand() and onDestroy() function and try clearing app from recent list and you will see onDestroy() is called. Android will re-start service if you have returned START_STICKY intent in onStartCommand()).
There are two approaches to fix your problem.
Either make your two services as foreground service.
Instead of using CheckAutoSyncReceivingOrder and CheckAutoSyncSendingOrder to schedule start of another services, you should use AlarmManager to schedule your task.

Stop background Service When application goes to background

I have background service in my android app,i start service from MainActivity onResume() method and it is work correctly.But how can i stop service when user press home button.Because currently when user press home button then application move to background and then user open some other app then after some time my service method is called and app force stop.Below is my code for start service -
Intent msgIntent = new Intent(mContext, MyBackgroundService.class);
startService(msgIntent);
Thanks in Advance.
EDITED
In My Service i use below code -
public void callAsynchronousTask() {
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
callWebservice();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
timer.schedule(doAsynchronousTask, START_DELAY, DELAY);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
callAsynchronousTask();
return Service.START_NOT_STICKY;
}
#Override
public void onCreate() {
mContext = this;
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
if(timer!=null){
timer.cancel();
}
stopSelf();
}
in my activity i use below code for stop service -
#Override
protected void onStop() {
try{
stopService(new Intent(this, MyBackgroundService.class));
isServiceRunning = false;
}
catch(Exception e){
e.printStackTrace();
}
super.onStop();
}
#Override
protected void onPause() {
try{
stopService(new Intent(this, MyBackgroundService.class));
isServiceRunning = false;
}
catch(Exception e){
e.printStackTrace();
}
super.onPause();
}
but my service is run while i use some other app and it force stop app.From background service i call some webservice and then store response of service in database.
Stop the service in onPause() and onStop()
mContext.stopService(new Intent(mContext,
MyBackgroundService.class))
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_HOME){
Log.e("home key pressed", "****");
// write your code here to stop the activity
enter code here
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onPause() {
Log.e("home key pressed on pause", "****");
// write your code here to stop your service
super.onPause();
}
the above code will keep check if user have pressed the home button or not.
when we open the other applications then our application(which was in background) gets cleared from the memory However the whole application does not removed but the some unwanted data and activities get finished.
In your case the activity which is to be updated gets cleared from the memory and your running background service when try to update the UI then it gets crashed by throwing NullPointerException.
So please saved the Reference of the activty(whose UI is to be updated) in onCreate() and set the reference to null in finish() method then check this reference in the background service if it is not null then update the UI otherwise no updation.
// Global Class for saving the reference
class GlobalReference{
public static <name_of_your_activity> activityRef;
}
in your activity
onCreate(){
GlobalReference.activityRef = this;
}
finish(){
GlobalReference.activityRef = null;
}
In your background service
if( GlobalReference.activityRef != null){
// update the UI of your activity
}
Hope this code will solve your issue.
Happy Coding...
press Home Button cause OnPause() function. Override onPause() and call stopService:
mContext.stopService(new Intent(mContext,
MyBackgroundService.class))

stopService() not working

I have an IntentService that does the following:
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Hello, World!");
}
}
The above is a sample of the code I am using. I intend to replace the println() with a HTTP Request sent to a server, but for now I am using this as a test. I call startService() as such:
#Override
public void onPause() {
ConnectionUtility.getInstance().startService(this);
super.onPause();
}
#Override
public void onDestroy() {
ConnectionUtility.getInstance().startService(this);
super.onDestroy();
}
#Override
public void onStop() {
ConnectionUtility.getInstance().startService(this);
super.onStop();
}
where my custom startService method does this:
public void startService(Activity activity) {
if (!isMyServiceRunning(activity)) {
Intent intent = new Intent(activity, BackgroundUpdateService.class);
activity.startService(intent);
}
}
Note: the isMyServiceRunning() method is a custom method I found elsewhere to determine if the Service is running. The method works as far as I know.
Now, the purpose of this Service is to trigger the println() whenever the particular Activity exits (either via onPause(), onDestroy() or onStop()), and when onCreate() or onResume() runs, the Service is to be stopped like so:
#Override
public void onResume() {
ConnectionUtility.getInstance().stopServiceIfRunning(this);
super.onResume();
}
Going one step deeper into stopServiceIfRunning():
public void stopServiceIfRunning(Activity activity) {
if (isMyServiceRunning(activity)) {
Intent intent = new Intent(activity, BackgroundUpdateService.class);
activity.stopService(intent);
}
}
Now here's the problem: I can start the Service alright, when I back out of the Activity via the Home/Back button or when I switch to a different Activity, the startService() method kicks in and it runs perfectly; that is to say, "Hello, World!" is printed every 5seconds as needed. But when I navigate back to the Activity, I can determine that my custom stopServiceIfRunning() method runs and the code enters the IF block fine (confirmed), but the service doesn't stop and the "Hello, World!"s just keep coming. What am I doing wrong?
---EDIT---
In response to Seraphim's comment:
private boolean isMyServiceRunning(Activity activity) {
ActivityManager manager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (BackgroundUpdateService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
But again, this method is returning true and false values accurately thus far, so I don't think this is the problem.
Finally figured out a way to do it, really really thankful to Seraphim for helping me out so much though.
I ended up overriding the onDestroy() method of my custom IntentService class. This is what I came up with:
public class BackgroundUpdateService extends IntentService {
private boolean status;
public BackgroundUpdateService() {
super("BackgroundUpdateService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
status = true;
// TODO Auto-generated method stub
while (status) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Hello, World!");
}
}
#Override
public void onDestroy() {
status = false;
super.onDestroy();
}
}
Evidently, the onDestroy() method is called whenever .stopService(intent) is called, so I made use of this fact to stop the while loop while I'm at it. This circumvents the reliability issue because each Service gets its own boolean variable and is not dependent on a static variable, and doesn't require any additional variables to be passed through the Intent.
Again, thanks to Seraphim for taking the time to help me out so much.
Stopping services is not a synchronous operation. If your check for service termination is close to the previous "service stop" call, you may find your service is still running.
In my app when I need to stop services (when exiting app) I enter in a loop cycle (using AsyncTask) and wait for service termination.
I see you call
#Override
public void onDestroy() {
ConnectionUtility.getInstance().startService(this);
super.onDestroy();
}
I suggest to use Application Context for starting and stopping your service and not the Activity as a context. Because you're starting your service when the activity is going to be destroyed!
Also the part
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Hello, World!");
}
}
A infinite loop when handling an intent? Sounds not very good to me.

How to call stopservice() method of Service class from the calling activity class

I am trying to call my service class's stopService() method from my activity.
But I dont know how to access stopservice method from my activity class.
I have the below code but its not working...........
This is HomeScreen class:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
enablecheck = (CheckBox)findViewById(R.id.enablecheck);
enablecheck.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(enablecheck.isChecked()){
startService(new Intent(HomeScreen.this, AutoService.class));
}else
{
stopService(new Intent(HomeScreen.this, AutoService.class));
}
}
});
}
This is Service Class:
public class AutoService extends Service {
private static final String TAG = "AutoService";
private Timer timer;
private TimerTask task;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "Auto Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
int delay = 5000; // delay for 5 sec.
int period = 5000; // repeat every sec.
timer = new Timer();
timer.scheduleAtFixedRate(task = new TimerTask(){
public void run()
{
System.out.println("done");
}
}, delay, period);
}
#Override
public boolean stopService(Intent name) {
// TODO Auto-generated method stub
timer.cancel();
task.cancel();
return super.stopService(name);
}
}
Any suggestion highly appreciable.
Thanks and Regards
Mintu
In fact to stopping the service we must use the method stopService() and you are doing in right way:
Start service:
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
startService(myService);
Stop service:
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
stopService(myService);
if you call stopService(), then the method onDestroy() in the service is called (NOT the stopService() method):
#Override
public void onDestroy() {
timer.cancel();
task.cancel();
Log.i(TAG, "onCreate() , service stopped...");
}
you must implement the onDestroy() method!.
Here is a complete example including how to start/stop the service.
I actually used pretty much the same code as you above. My service registration in the manifest is the following
<service android:name=".service.MyService" android:enabled="true">
<intent-filter android:label="#string/menuItemStartService" >
<action android:name="it.unibz.bluedroid.bluetooth.service.MY_SERVICE"/>
</intent-filter>
</service>
In the service class I created an according constant string identifying the service name like:
public class MyService extends ForeGroundService {
public static final String MY_SERVICE = "it.unibz.bluedroid.bluetooth.service.MY_SERVICE";
...
}
and from the according Activity I call it with
startService(new Intent(MyService.MY_SERVICE));
and stop it with
stopService(new Intent(MyService.MY_SERVICE));
It works perfectly. Try to check your configuration and if you don't find anything strange try to debug whether your stopService get's called properly.
#Juri
If you add IntentFilters for your service, you are saying you want to expose your service to other applications, then it may be stopped unexpectedly by other applications.
That looks like it should stop the service when you uncheck the checkbox. Are there any exceptions in the log? stopService returns a boolean indicating whether or not it was able to stop the service.
If you are starting your service by Intents, then you may want to extend IntentService instead of Service. That class will stop the service on its own when it has no more work to do.
AutoService
class AutoService extends IntentService {
private static final String TAG = "AutoService";
private Timer timer;
private TimerTask task;
public onCreate() {
timer = new Timer();
timer = new TimerTask() {
public void run()
{
System.out.println("done");
}
}
}
protected void onHandleIntent(Intent i) {
Log.d(TAG, "onHandleIntent");
int delay = 5000; // delay for 5 sec.
int period = 5000; // repeat every sec.
timer.scheduleAtFixedRate(timerTask, delay, period);
}
public boolean stopService(Intent name) {
// TODO Auto-generated method stub
timer.cancel();
task.cancel();
return super.stopService(name);
}
}
In Kotlin you can do this...
Service:
class MyService : Service() {
init {
instance = this
}
companion object {
lateinit var instance: MyService
fun terminateService() {
instance.stopSelf()
}
}
}
In your activity (or anywhere in your app for that matter):
btn_terminate_service.setOnClickListener {
MyService.terminateService()
}
Note: If you have any pending intents showing a notification in Android's status bar, you may want to terminate that as well.

Categories

Resources