How do I run a parallel action (process)
to the main app in Android?
I know that, there are a lot of ways to do it: Threads
, Tasks
, Handlers
and etc'...
This is the way I chose. But I think it takes a lot of memory and doesn't closes in the interrupt call.
checkReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO: Check is this a good way to handle threads
Thread t = new Thread() {
@Override
public void run() {
internetConnectionManager.TryConnect();
this.interrupt();
}
};
t.start();
}
}
};
Two things wrong with your arroach:
onRecieve
method. The reason is explained here :This has important repercussions to what you can do in an onReceive(Context, Intent) implementation: anything that requires asynchronous operation is not available, because you will need to return from the function to handle the asynchronous operation, but at that point the BroadcastReceiver is no longer active and thus the system is free to kill its process before the asynchronous operation completes
Thread.currentThread().interrupt()
does not make any sense in your example since your thread is already done by that line and will finish, and also because you don not check interrupted
flag anyway.The better way, in my opinion, would be to start a simple IntentService from your onReceive
code. Here is a simple tutorial.
Important edit based on FunkTheMonk's comment:
If the broadcast comes from an alarm or external event, it is possible that your device will go to sleep shortly after onReceive
returns (even if you create a service). If that is the case, instead of using regular BroadCastReceiver
you should extend WakefulBroadcastReceiver from support library.