How do I terminate HandlerThreads? - android

Following Googles examples for using a Service, I created a couple of threads like this. I can't use IntentService, because I'm doing something that involves waiting for callbacks.
However, I don't know how to terminate a Thread started in this manner. As I understand it, Threads automatically terminate when the run() method returns. However, this kind of thread doesn't have a run method. My Threads are leaking--they stay alive after stopSelf().
#Override
public void onCreate() {
HandlerThread thread = new HandlerThread("ServiceStartArguments",
android.os.Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
HandlerThread thread2 = new HandlerThread("CallbackHandling",
android.os.Process.THREAD_PRIORITY_BACKGROUND);
thread2.start();
mServiceLooper = thread.getLooper();
mCallbackLooper = thread2.getLooper();
mServiceHandler = new MyHandler(mServiceLooper);
mCallbackHandler = new Handler(mCallbackLooper);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
// For each start request, send a message to start a job and deliver the
// start ID so we know which request we're stopping when we finish the job
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
mMainThreadHandler=new Handler();
// If we get killed, after returning from here, restart
return START_STICKY;
}
private final class MyHandler extends Handler {
public MyHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
cycle();
// Stop the service using the startId, so that we don't stop
// the service in the middle of handling another job
stopSelf(msg.arg1);
}
}
protected void cycle() {
...
mCallbackHandler.post(new Runnable(){
public void run(){
goAskForSomeCallbacks();
}
});
try {
Thread.sleep(GIVE_UP_TIME);
} catch (InterruptedException e){
//The callback will interrupt this thread to stop it from waiting
Log.d(TAG,"Got early callback, stop waiting.");
}
Thread.interrupted(); //clear the interrupt
doStuff();
}

Try calling the quit method on the corresponding Loopers.

You can call quit method on your handler threads.
e.g.
thread.quit();
thread2.quit();

You can also use the following recommended approach:
but be careful before using it because it cancels all pending jobs
handler.quitSafely();

Force closing the app does it but otherwise they just keep going on their own.

Related

How to close a background thread in a service when the service get destroyed

I want to close a background thread in my service in the onDestroy method, because if I stop my service the background thread is still running. Because thread.stop() is deprecated, I don't really know how to do it.
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
runAsForeground();
Runnable service = new Runnable() {
#Override
public void run() {
connect(client,options);
}
};
backgroundThread = new Thread(service);
backgroundThread.start();
Log.i(TAG, "onStartCommand methode called");
return Service.START_NOT_STICKY;
}
Thread life cycle is not the same as Android Context Component life cycle. Stopping the service is not enough to stop the thread which service created. Thread.interrupt() is a option. - You should catch InterruptedException though. If it is not enough, you can check if service is not stopped inside your connect() method.
I suppose you're using a Service. Then you can Context.stopService(intent) just the same way you Context.startService(intent).
You can use
stopService(new Intent(this, YourService.class));
It will stop this service and all its Threads.

background service for Notification is not working

I tried to use the following code trigger toast as background service but it gets executed for 20 times, it was not working till 100. With thread it is not working gives error.
Felt service get destroyed.
How to trigger notification with 30 minutes difference as a background service, though app is closed,
I need to display Good morning, Good Afternoon, Good Evening and Good night as a Notification.
without any internet support.
Is following procedure not ok? I think so. How to do this?
import android.app.Service;
public class HelloService extends Service {
private static final String TAG = "HelloService";
int i=0;
private boolean isRunning = false;
#Override
public void onCreate() {
Log.i(TAG, "Service onCreate");
Toast.makeText(this, " On create Hello Service Started", Toast.LENGTH_LONG).show();
isRunning = true;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service onStartCommand");
for (;i<100; i++) {
try {
// Thread.sleep(1000);
Toast.makeText(getApplicationContext(), "Hello Service On Loop"+i , Toast.LENGTH_LONG).show();
//
} catch (Exception e) {
}
}
//Stop service once it finishes its task
// i++;
stopSelf();
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
Log.i(TAG, "Service onBind");
return null;
}
#Override
public void onDestroy() {
isRunning = false;
Log.i(TAG, "Service onDestroy");
}
}
onStartCommand() is called on the main (UI) thread. If you execute a loop inside onStartCommand(), Android will kill the process after about 30 seconds with an ANR (Application Not Responding) because you cannot block the main (UI) thread.
You can do what you want either using AlarmManager to set a timer that will start your Service or trigger a BroadcastReceiver at certain times, or you can post a Runnable to a Handler in onStartCommand() with a certain delay and do whatever you want in the Runnable, or you can start a background thread in onStartCommand() and the background thread can loop and sleep or whatever and then do what you want.
In any case, you cannot show a Toast every second. This will flood the UI with toasts and either Android will dump most of them (ignore them) or the UI will be so busy showing them that Android will kill your app due to ANR or the user will just uninstall your app!

Android: Unable to perform a task repeatedly using android service

I have written a service in android.I want to repeatedly perform a task using service. That is the service shouldn't die and should perform the task repeatedly. However,the service performs the task just once and then gets killed.How to perform the task repeatedly in background.
My current code is->
public class SyncService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
#Override
public void onCreate() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(SyncService.this, "servicestarting", Toast.LENGTH_SHORT).show();
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}
#Override
public void onDestroy() {
Toast.makeText(SyncService.this, "service done", Toast.LENGTH_SHORT).show();
}
// Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
Toast.makeText(SyncService.this, "repeatedly perform some task", Toast.LENGTH_SHORT).show();
//constantly perform task here
}
}
}
How to repeatedly perform some task using service?
Well you only send one message to the Handler. So that message will be processed once. You could have the Handler pass the same message back again, but with no delay that isn't a good idea- you'll deadlock the main thread. The best way to do something repeatedly would be to spin off a Thread and do it in the Thread, with the Thread's Runnable looping forever.

app forceclose while running in background

In my android app i have one service which calls some webservices after a fix interval.
App is running perfectly in foreground and refresh data,but when user exit from app and use some other app then my app force close after many times.
Why this app force close while running in background.
Code that i was using for start service -
msgIntent = new Intent(mContext, MyBackgroundService.class);
startService(msgIntent);
and inside onDestroy() of my main activity i have following code to stop service-
if(msgIntent!=null){
stopService(msgIntent);
}
background service call some async task and each aync task onPostExecute() method execute some insert statement in database.
i am not geting why this force close occure.
Please give your comments.
Thanks in advance.
My Service Code
#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;
}
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer 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);
}
Actually the problem is here
if(msgIntent!=null){
stopService(msgIntent);
}
in your onDestroy(). Because when you close your application so this above code gets called which is closing your service.
And after closing service again you are trying to insert data by calling service + web service. Hence, there is no service object thats why it gets crashed.
To handle this scenario, you need to comment above code which is in onDestroy() & then check/run it, will solve your problem. & there you need to stop your service by other ways. Go step by step.
you stop the service at onDestroy() method. but services are not depend the activity. So try to neglect the stop service.
(or)
try
{
//stop service code
}
catch(Exception e)
{
}
try this.

Android: Developing apps that run in the 'background', how?

I am used to developing standalone applications, ones that you click on, it runs, and when you are done, you exit.
I am now interested in tackling a new type (not sure if that's the right word) of app, and was wondering how I should go about it. I am not sure what to research, and would appreciate your advice to help me get the ball rolling. I'll give you an idea about what I have in mind.
My app would need to perform a special action in the dialer. When the user dials a number and is in the middle of a call, I would like the user to be able to press the Menu key, and find an option to scroll through all their contacts (either the stock app, or my own list which I grab from the contacts stored in the phone), and select one. Upon selection, that contact's number is pasted into the dialer (keep in mind, in the middle of a call).
I certainly don't expect an answer telling me how to do this exactly, I just need some guidance as I have never written an app of this nature before. On top of that, is it even possible to do what I want to do?
Thank you.
You need to go through Android Service or IntentService. A Service is an application component that can perform long-running operations in the background and does not provide a user interface(UI).
The following example is taken from android blog which is an implementation of the Service class
public class HelloService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
// Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
long endTime = System.currentTimeMillis() + 5*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
// Stop the service using the startId, so that we don't stop
// the service in the middle of handling another job
stopSelf(msg.arg1);
}
}
#Override
public void onCreate() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
// For each start request, send a message to start a job and deliver the
// start ID so we know which request we're stopping when we finish the job
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}
#Override
public void onDestroy() {
Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}
}
On the other hand, The same thing can be achieved using IntentService, which is a base class for Services that handle asynchronous requests on demand.
public class HelloIntentService extends IntentService {
/**
* A constructor is required, and must call the super IntentService(String)
* constructor with a name for the worker thread.
*/
public HelloIntentService() {
super("HelloIntentService");
}
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
#Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
long endTime = System.currentTimeMillis() + 5*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
}
}
You can also go through SO post https://stackoverflow.com/a/4353653/432903
If your app isn't mainly written in javascript/webview/phonegap, then all you have to do is look at the Service class. That class and the linked documents tell you everything you need to know.
maybe you can use an IntentFilter so you can get a system notify when the user uses a dialer.
and you should learn the Service component which can work in background in android.

Categories

Resources