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”异常。

相关内容

热门资讯

值得注意的是!wepoker免... 值得注意的是!wepoker免费透视(透视)新上游辅助(好像有辅助工具)-哔哩哔哩1、首先打开新上游...
透视讲解!wepoker科技辅... 透视讲解!wepoker科技辅助器(透视)江西中至黑科技辅助软件(总是有辅助辅助器)-哔哩哔哩一、江...
透视中牌率!hhpoker德州... 透视中牌率!hhpoker德州透视挂(透视)潮汕激k脚本(果然是有辅助平台)-哔哩哔哩1、上手简单,...
透视好友房!竞技联盟透视插件(... 透视好友房!竞技联盟透视插件(透视)涂山山西辅助(本来真的有辅助辅助器)-哔哩哔哩1、涂山山西辅助透...
据了解!拱趴大菠萝十三水作必弊... 据了解!拱趴大菠萝十三水作必弊(透视)微信小程序辅助工具(其实是真的辅助软件)-哔哩哔哩1、用户打开...
透视讲解!约局吧德州有挂吗(透... 透视讲解!约局吧德州有挂吗(透视)多乐跑胡子辅助(一直是真的辅助平台)-哔哩哔哩1、让任何用户在无需...
透视脚本!wpk辅助(透视)7... 透视脚本!wpk辅助(透视)789大菠萝有挂吗(确实有辅助安装)-哔哩哔哩1、透视脚本!wpk辅助(...
透视挂!wepoker有透视功... 透视挂!wepoker有透视功能吗(透视)微信小程序微乐家乡辅助器(都是真的是有辅助软件)-哔哩哔哩...
近日!wepoker破解器有用... 近日!wepoker破解器有用吗(透视)福建天天开心辅助工具下载(果然有辅助下载)-哔哩哔哩1、完成...
透视总结!hhpoker一直输... 透视总结!hhpoker一直输有挂吗(透视)开心庄园辅助器免费(一直真的是有辅助平台)-哔哩哔哩1、...