android从广播接收器启动服务

问题描述 投票:0回答:2

当应用程序被终止且服务保持活动状态时,如何从广播接收器启动服务。 我的广播接收器:

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);
    }
}

}

应用程序启动后,一切正常。但是当我杀死应用程序时,我只看到吐司,服务正在睡觉。请帮助我!

android service broadcastreceiver
2个回答
2
投票

摘自“SirKnigget”的回答这里

可能会改变

启动服务(...)

启动前景(...)

还要小心退出应用程序

系统.退出(0)

服务将停止。所以使用

完成()

退出应用程序。

您可以从 http://developer.android.com/reference/android/app/Service.html

找到更多信息

希望这有助于解决您的问题。


0
投票

我最近也遇到了类似的问题。我想使用服务执行某些任务,例如在触发广播接收器后显示浮动窗口,但应用程序不断抛出BackgroundServiceStartNotAllowedException。

对我来说,无需过多更改代码的情况下,我在广播接收器中初始化了 Worker,并且 Worker 除了启动前台服务之外什么也不做。我的应用程序现在运行良好,即使它在后台被杀死。如有任何疑问,请随时发表评论。干杯!

© www.soinside.com 2019 - 2024. All rights reserved.