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

相关内容

热门资讯

避坑细节!hh poker辅助... 避坑细节!hh poker辅助器先试用(辅助挂)果然是真的有挂(有挂秘笈)1、hh poker辅助器...
发现一款!佛手在线有挂吗(辅助... 您好,佛手在线有挂吗这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家...
来一盘!wepoker怎么提高... 来一盘!wepoker怎么提高运气(辅助挂)本来是真的有挂(有人有挂)1、wepoker怎么提高运气...
揭秘一下!悟空黑桃a有挂嘛(辅... 揭秘一下!悟空黑桃a有挂嘛(辅助挂)本来是真的有挂(有挂方略)悟空黑桃a有挂嘛能透视中分为三种模型:...
玩家必看教程!wepoker可... 玩家必看教程!wepoker可以免费玩吗(辅助挂)一贯有挂(确实有挂)1、首先打开wepoker可以...
玩家爆料!wejoker辅助器... 玩家爆料!wejoker辅助器怎么卖(辅助挂)好像是真的有挂(有挂教程)玩家爆料!wejoker辅助...
一秒答解!wepokerh5破... 一秒答解!wepokerh5破解(辅助挂)确实是真的有挂(有挂方法)1、进入到wepokerh5破解...
我来教大家!wepoker怎么... 我来教大家!wepoker怎么看牌型(辅助挂)一直是真的有挂(有挂头条)1)wepoker怎么看牌型...
一分钟揭秘!aapoker插件... 一分钟揭秘!aapoker插件下载(辅助挂)果然是有挂(有挂方针)1、起透看视 aapoker插件下...
教程攻略!wepoker免费透... 教程攻略!wepoker免费透视(辅助挂)确实是有挂(有挂透视)1、这是跨平台的wepoker免费透...