billy gates
billy gates

Reputation: 185

android start service from broadcast receiver

How to start service from broadcast receiver when application is killed and service stay alive. My BroadcastReceiver:

public class NetworkChangeReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
    final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    Intent intent1 = new Intent(context, ImageUploader.class);
    if (wifi != null && wifi.isAvailable()) {
        context.startService(intent1);
        Toast.makeText(context, "start service execute", Toast.LENGTH_SHORT).show();
    } else if(mobile != null && mobile.isAvailable()) {
        context.startService(intent1);
    }
}

}

When application is started, all work fine. But when i killed app, i see only toast, service was sleeping. Please help me!

Upvotes: 1

Views: 650

Answers (2)

Arpit Jaiswal
Arpit Jaiswal

Reputation: 1

I have recently faced the similar issue. I wanted to do certain tasks with service like displaying floating window after broadcast receiver get triggered but the application keep throwing the BackgroundServiceStartNotAllowedException.

What worked for me without altering the code much is that I initialized Worker in broadcast receiver and Worker does nothing but start the foreground service. My application now is doing fine, even if the it is killed in the background. feel free to comment in case of any doubt. Cheers!

Upvotes: 0

HailNaRoz
HailNaRoz

Reputation: 106

From the answer of "SirKnigget" in Here

It may be change from

startService(...)

to

startForeground (...)

And also careful about quit the application by

System.exit(0)

The services will stop. So use

finish()

to exit from the application.

You can find additional information from http://developer.android.com/reference/android/app/Service.html

Hope this help to solve your problem.

Upvotes: 2

Related Questions