3

I have used Intent to open Location Settings menu to enable gps in my Activity.After calling Intent I have used a Service to listen to the location updates.I sent two BroadcastReceivers from Service to Activity.In the onResume() method of the Activity I want to access the data passed from the Service.But when I click the back button the app is crashed.It says that BroadcastReceiver has not been registered.But I have registered both the BroadcastReceivers.

Error:

java.lang.RuntimeException: Unable to destroy activity {com.example.jobinsabu.ohxee/com.example.jobinsabu.ohxee.AddOffers.AddOffers}: java.lang.IllegalArgumentException: Receiver not registered: com.example.jobinsabu.ohxee.AddOffers.AddOffers$7@8cd71b4 at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:4137) at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:4155) at android.app.ActivityThread.access$1500(ActivityThread.java:177) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1484) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5910) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200) Caused by: java.lang.IllegalArgumentException: Receiver not registered: com.example.jobinsabu.ohxee.AddOffers.AddOffers$7@8cd71b4 at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:830) at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1850) at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:518) at com.example.jobinsabu.ohxee.AddOffers.AddOffers.onDestroy(AddOffers.java:448) at android.app.Activity.performDestroy(Activity.java:6418) at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1153) at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:4124) at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:4155)  at android.app.ActivityThread.access$1500(ActivityThread.java:177)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1484)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5910)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200) 

Code:

StatsGpsService.java

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);

        }
    }
Vishal Chhodwani
  • 2,567
  • 5
  • 27
  • 40
jobin
  • 1,489
  • 5
  • 27
  • 52

2 Answers2

7

That is because - you are unregistering the broadcastreceivers in both the method onStop() and onDestroy().

You must unregister the receiver only at once. Try removing unregister code from onStop() method.

Paresh P.
  • 6,677
  • 1
  • 14
  • 26
  • I actually want to unregister the broadcast receiver as soon as the data is accessed – jobin Mar 08 '17 at 12:31
  • then, write the unregister code where your data becomes accessed. and don't forget to put in `try... catch`. Unregistering multiple times doesn't make sense. What happens is your `receiver` is not `null` but it is already unregistered. – Paresh P. Mar 08 '17 at 12:34
  • i want to unregister below offer_lat_txt.setText(lat); offr_long_inpt.setText(longt); in the onReceive() method which I think may give me error – jobin Mar 08 '17 at 12:45
  • Try adding code over there... There is nothing to worry about. – Paresh P. Mar 08 '17 at 12:51
  • please wait..I am trying that – jobin Mar 08 '17 at 12:57
  • hmmm.I tried that. It shows the exception is at unregisterReceiver(broadcastReceiver1); in onDestroy method – jobin Mar 08 '17 at 12:59
  • Remove unregister code from `onStop` and `onDestroy` totally. Remember you need to unregister receiver once you are done with that. – Paresh P. Mar 08 '17 at 13:02
  • I have unregistered both the broadcast receivers below offer_lat_txt.setText(lat); offr_long_inpt.setText(longt); and removed the code in onstop() and on destroy().Now I get Error receiving broadcast intent – jobin Mar 08 '17 at 13:08
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/137557/discussion-between-wizard-and-jobin). – Paresh P. Mar 08 '17 at 13:12
1

it is Best practice to register Broadcast Receiver in onResume() and Stop them in onPause()

Add this code:

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

leave onStop() and onDestroy()

rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
  • did u remove the onstop, ondestroy implementation? from above code app will not crash..if any exception occurs it should be in try/catch . – rafsanahmad007 Mar 08 '17 at 12:50