简体   繁体   中英

Notice fragment or activity from broadcast receiver

I need notice fragment/activity from broadcast receiver but I cant find solution.

Description: When fragment start my method check if GPS module is ON if no ask user to turn it on. Now I have broadcast receiver for gps and when is gps On or OFF I get message, this works. But now I need do something like interface and when i receive GPS on/off I want call my method in fragment. Im not sure if is clear what I need. Here I try it with interface but then I find so I cant pass interface object to broadcast receiver constructor.

My solution with interface but not working:

    public class GpsLocationReceiver extends BroadcastReceiver {

    private INotifyGpsTurnedOn iNotifyGpsTurnedOn = null;

    public GpsLocationReceiver(INotifyGpsTurnedOn iNotifyGpsTurnedOn) {
        this.iNotifyGpsTurnedOn = iNotifyGpsTurnedOn;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        LocationManager lm = (LocationManager) context.getSystemService(Service.LOCATION_SERVICE);
        boolean isEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        Toast.makeText(context, isEnabled+"",
                Toast.LENGTH_SHORT).show();

        if(isEnabled){
            iNotifyGpsTurnedOn.iniGps();
        }
        else{
            iNotifyGpsTurnedOn.askTurnOnGps();
        }
    }

    public interface INotifyGpsTurnedOn {
        public void iniGps();
        public void askTurnOnGps();
    }
}

In fragment class I have implement interface with methods, register receiver etc ...

 GpsLocationReceiver m_gpsChangeReceiver = new GpsLocationReceiver(this);
    getActivity().registerReceiver(m_gpsChangeReceiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));

    @Override
public void iniGps() {
    mGps.startGps(false);
}

@Override
public void askTurnOnGps() {
    mGps.askUserToTurnOnGPS(getActivity());
}

This works just fine. You can declare an Interface and provide this in the constuctor. This works as long as you instantiate the BroadcastReceiver yourself, and don't let Android do it. You don't need to declare this BroadcastReceiver in the manifest.

The reason you are getting Exception: Unable to instantiate receiver no empty constructor. is because Android is trying to instantiate the BroadcastReceiver . (for whatever reason).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM