Android广播接收器未注册错误。

3

我在Activity中使用Intent打开位置设置菜单来启用GPS。调用Intent后,我使用了一个Service来监听位置更新。我从Service向Activity发送了两个BroadcastReceivers。在Activity的onResume()方法中,我想要访问从Service传递过来的数据。但是当我点击返回按钮时,应用程序崩溃了。它说BroadcastReceiver未注册。但我已经注册了两个BroadcastReceivers。

错误:

java.lang.RuntimeException: 无法销毁活动 {com.example.jobinsabu.ohxee/com.example.jobinsabu.ohxee.AddOffers.AddOffers}: java.lang.IllegalArgumentException: 接收器未注册:com.example.jobinsabu.ohxee.AddOffers.AddOffers$7@8cd71b4      在android.app.ActivityThread.performDestroyActivity(ActivityThread.java:4137)      在android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:4155)      在android.app.ActivityThread.access$1500(ActivityThread.java:177)      在android.app.ActivityThread$H.handleMessage(ActivityThread.java:1484)      在android.os.Handler.dispatchMessage(Handler.java:102)      在android.os.Looper.loop(Looper.java:135)      在android.app.ActivityThread.main(ActivityThread.java:5910)      在java.lang.reflect.Method.invoke(Native Method)      在java.lang.reflect.Method.invoke(Method.java:372)      在com.android.internal.os.ZygoteInit $MethodAndArgsCaller.run(ZygoteInit.java:1405)      在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)     导致:java.lang.IllegalArgumentException: 接收器未注册:com.example.jobinsabu.ohxee.AddOffers.AddOffers$7@8cd71b4      在android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:830)      在android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1850)      在android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:518)      在com.example.jobinsabu.ohxee.AddOffers.AddOffers.onDestroy(AddOffers.java:448)      在android.app.Activity.performDestroy(Activity.java:6418)      在android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1153)      在android.app.ActivityThread.performDestroyActivity(ActivityThread.java:4124)      在android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:4155)      在android.app.ActivityThread.access$1500(ActivityThread.java:177)      在android.app.ActivityThread$H.handleMessage(ActivityThread.java:1484)      在android.os.Handler.dispatchMessage(Handler.java:102)      在android.os.Looper.loop(Looper.java:135)      在android.app.ActivityThread.main(ActivityThread.java:5910)      在java.lang.reflect.Method.invoke(Native Method)      在java.lang.reflect.Method.invoke(Method.java:372)      在com.android.internal.os.ZygoteInit $MethodAndArgsCaller.run(ZygoteInit.java:1405)      在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
public class StatsGpsService extends Service {
    LocationListener locationListener;
    LocationManager locationManager;
    boolean flag1;

    public StatsGpsService() {
        super();

    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("Service","Created");


    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        handleLocation(intent);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("Service","Destroyed");
    }

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

    public void handleLocation(Intent intent){
        if(intent!= null) {
            flag1 = intent.getBooleanExtra("offr_act_ind", false);

            locationListener = new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    if (flag1 == true) {

                        Intent intent = new Intent("loc_updts");
                        intent.putExtra("stat_lat", location.getLatitude());
                        intent.putExtra("stat_longt", location.getLongitude());
                        sendBroadcast(intent);
                    }
                }

                @Override
                public void onStatusChanged(String s, int i, Bundle bundle) {

                }

                @Override
                public void onProviderEnabled(String s) {

                }

                @Override
                public void onProviderDisabled(String s) {
                    Log.e("Provider","Disabled");
                    Intent intent1=new Intent("offr_prvdr_disable");
                    intent1.putExtra("offr_provider_disable",true);
                    sendBroadcast(intent1);

                }
            };
            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);


            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }

            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
        }
    }
}

AddOffers.java:

 @Override
    protected void onResume() {
        super.onResume();
 broadcastReceiver1 =new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if(intent!=null){
                    if(intent.getBooleanExtra("offr_provider_disable",false)==true){
                        offer_gps=false;
                        Log.e("gps","disabled");
                    }
                }
            }
        };
        this.registerReceiver(broadcastReceiver1,new IntentFilter("offr_prvdr_disable"));

        broadcastReceiver=new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
            if(intent!=null){
                lat=Double.toString(intent.getDoubleExtra("stat_lat",0.0));
                longt=Double.toString(intent.getDoubleExtra("stat_longt",0.0));
                offer_lat_txt.setText(lat);
                offr_long_inpt.setText(longt);
                }
            }
        };
        this.registerReceiver(broadcastReceiver,new IntentFilter("loc_updts"));

       }

    @Override
    protected void onStop() {
        super.onStop();
    if(static_gps_intent!=null){

        stopService(static_gps_intent);

    }
        if(broadcastReceiver1!=null){
            unregisterReceiver(broadcastReceiver1);
        }
        if(broadcastReceiver!=null){
            unregisterReceiver(broadcastReceiver);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(broadcastReceiver1!=null){
            unregisterReceiver(broadcastReceiver1);
        }
        if(broadcastReceiver!=null){
            unregisterReceiver(broadcastReceiver);
        }
        if(static_gps_intent!=null){

            stopService(static_gps_intent);

        }
    }

你在清单文件中声明了吗? - Ranjan
在清单文件中声明的服务 - jobin
可能会有帮助:https://dev59.com/CG025IYBdhLWcg3wLizo#6165317 - Shashidhar Mayannavar
始终在 onStart 方法中进行注册。 - Raja Jawahar
2个回答

7
那是因为 - 你在 onStop()onDestroy() 方法中都注销了 broadcastreceiver。你必须只在一个地方注销接收器。尝试从 onStop() 方法中移除注销代码。

我实际上想在数据被访问后立即注销广播接收器。 - jobin
然后,在您的数据被访问时编写注销代码,并不要忘记放入 try...catch。多次注销没有意义。发生的情况是您的 receiver 不为 null,但已经被注销了。 - user2756345
尝试在那里添加代码... 没有什么好担心的。 - user2756345
请等一下,我正在尝试翻译相关的编程内容。 - jobin
完全从onStoponDestroy中删除取消注册代码。请记住,一旦完成,您需要注销接收器。 - user2756345
显示剩余4条评论

1

最佳实践是在onResume()中注册广播接收器,并在onPause()中停止它们。

添加以下代码:

protected void onPause() {
    try{ 
        if(reciever != null) {
            this.unregisterReceiver(reciever);
          }
        } catch (Exception e){
          // already unregistered
          }
        super.onPause();
    }

保留 onStop()onDestroy()


你移除了 onStop 和 onDestroy 的实现吗?如果从上面的代码中移除了,应用程序将不会崩溃。如果出现任何异常,应该在 try/catch 中处理。 - rafsanahmad007

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接