Android前台服务一直抛出“java.lang.IllegalArgumentException: Service not registered”异常。
创始人
2024-10-09 15:02:10
0

出现“java.lang.IllegalArgumentException: Service not registered”异常通常是因为在解绑服务之后,前台服务仍然尝试取消注册未被注册的接收器。

以下是一个解决方法的代码示例:

public class MyService extends Service {
    private MyReceiver myReceiver;
    private boolean isRegistered = false;

    @Override
    public void onCreate() {
        super.onCreate();
        // 创建广播接收器
        myReceiver = new MyReceiver();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 注册广播接收器
        if (!isRegistered) {
            registerReceiver(myReceiver, new IntentFilter("com.example.myaction"));
            isRegistered = true;
        }
        
        // 将服务设置为前台服务
        Notification notification = new Notification.Builder(this)
                .setContentTitle("My Service")
                .setContentText("Running...")
                .setSmallIcon(R.drawable.ic_notification)
                .build();
        startForeground(1, notification);
        
        // 执行其他任务
        
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 解绑服务时取消注册广播接收器
        if (isRegistered) {
            unregisterReceiver(myReceiver);
            isRegistered = false;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    // 自定义广播接收器
    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 处理接收到的广播消息
        }
    }
}

在此示例中,我们创建了一个前台服务MyService,并在onStartCommand方法中注册广播接收器MyReceiver。在onDestroy方法中,解绑服务时取消注册广播接收器。

请确保在取消注册广播接收器之前,先判断广播接收器是否已注册。这样可以避免重复取消注册未注册的接收器,从而避免抛出“java.lang.IllegalArgumentException: Service not registered”异常。

相关内容

热门资讯

刚刚!wpk透视是真的假的(透... 刚刚!wpk透视是真的假的(透视)本来真的是有辅助平台(有挂解惑)-哔哩哔哩1、每一步都需要思考,不...
透视真的!云扑克有透视吗(透视... 透视真的!云扑克有透视吗(透视)竟然真的是有辅助工具(有挂透视)-哔哩哔哩1、金币登录送、破产送、升...
透视真的!wepoker透视器... 透视真的!wepoker透视器免费(透视)都是有辅助工具(的确有挂)-哔哩哔哩一、wepoker透视...
据相关数据显示!epoker底... 据相关数据显示!epoker底牌透视(透视)原来是有辅助神器(有挂详情)-哔哩哔哩小薇(辅助器软件下...
据玩家消息!hhpoker透视... 据玩家消息!hhpoker透视脚本下载(透视)切实有辅助插件(有挂神器)-哔哩哔哩1、上手简单,内置...
透视安装!拱趴大菠萝怎么开挂(... 透视安装!拱趴大菠萝怎么开挂(透视)切实真的有辅助软件(有挂细节)-哔哩哔哩1、用户打开应用后不用登...
目前来看!wepoker破解工... 目前来看!wepoker破解工具(透视)确实存在有辅助app(发现有挂)-哔哩哔哩该软件可以轻松地帮...
围绕透视问题!hhpoker辅... 围绕透视问题!hhpoker辅助器(透视)其实有辅助软件(有挂方法)-哔哩哔哩1、打开软件启动之后找...
透视黑科技!hhpoker有辅... 透视黑科技!hhpoker有辅助吗(透视)总是真的是有辅助平台(发现有挂)-哔哩哔哩1、很好的工具软...
于此同时!wepoker透视是... 于此同时!wepoker透视是真的吗(透视)确实存在有辅助app(有挂头条)-哔哩哔哩1、实时wep...