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

相关内容

热门资讯

解迷透视!红龙poker辅助工... 解迷透视!红龙poker辅助工具!切实是有辅助教程(有挂教程)-哔哩哔哩1、红龙poker辅助工具辅...
详情透视!pokemmo辅助官... 详情透视!pokemmo辅助官网!其实有辅助软件(发现有挂)-哔哩哔哩1、玩家可以在pokemmo辅...
必备透视!wepoker透视有... 必备透视!wepoker透视有吗!竟然有辅助教程(真是有挂)-哔哩哔哩1、点击下载安装,wepoke...
解谜透视!红龙poker辅助工... 解谜透视!红龙poker辅助工具!其实真的是有辅助插件(有挂秘笈)-哔哩哔哩1、下载好红龙poker...
必备透视!pokemmo辅助脚... 必备透视!pokemmo辅助脚本!都是是真的有辅助神器(存在有挂)-哔哩哔哩所有人都在同一条线上,像...
教你透视!pokemmo辅助器... 教你透视!pokemmo辅助器!真是是真的有辅助app(有挂技术)-哔哩哔哩1、完成pokemmo辅...
专业透视!德州透视是真的假的!... 专业透视!德州透视是真的假的!一直存在有辅助工具(有挂秘笈)-哔哩哔哩1、德州透视是真的假的破解器简...
解迷透视!德州局脚本!竟然一直... 解迷透视!德州局脚本!竟然一直都是有辅助方法(有挂教程)-哔哩哔哩1、打开软件启动之后找到中间准星的...
分享透视!聚星ai辅助工具下载... 分享透视!聚星ai辅助工具下载!原来有辅助神器(有挂秘笈)-哔哩哔哩1、超多福利:超高返利,海量正版...
科普透视!werplan外开挂... 科普透视!werplan外开挂!总是真的有辅助技巧(有挂方略)-哔哩哔哩1、下载好werplan外开...