簡體   English   中英

通知來自廣播接收器的片段或活動

[英]Notice fragment or activity from broadcast receiver

我需要廣播接收機的通知片段/活動,但找不到解決方案。

說明:當片段啟動我的方法時,如果沒有要求用戶打開GPS模塊,請檢查GPS模塊是否為ON。 現在,我已經為gps廣播了接收器,並且當gps開啟或關閉時,我收到消息,這可行。 但是現在我需要做一些類似界面的事情,當我打開/關閉GPS時,我想分段調用我的方法。 我不確定是否清楚我需要什么。 在這里,我嘗試使用接口,但隨后發現,因此無法將接口對象傳遞給廣播接收器構造函數。

我的界面解決方案不起作用:

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

在片段類中,我具有與方法,寄存器接收器等的實現接口...

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

這樣很好。 您可以聲明一個Interface並在構造函數中提供它。 只要您自己實例化BroadcastReceiver ,並且不要讓Android執行此操作,此方法就起作用。 您無需在清單中聲明此BroadcastReceiver

出現Exception: Unable to instantiate receiver no empty constructor.的原因Exception: Unable to instantiate receiver no empty constructor. 因為Android試圖實例化BroadcastReceiver (無論出於何種原因)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM