gpt4 book ai didi

java - 来自广播接收器的通知 fragment 或 Activity

转载 作者:行者123 更新时间:2023-11-30 02:26:41 25 4
gpt4 key购买 nike

我需要来自广播接收器的通知 fragment/Activity ,但我找不到解决方案。

描述:当 fragment 启动时,我的方法检查 GPS 模块是否打开,如果没有要求用户打开它。现在我有 gps 的广播接收器,gps 何时打开或关闭我收到消息,这有效。但是现在我需要做一些类似界面的事情,当我收到 GPS 开/关时,我想在 fragment 中调用我的方法。我不确定我是否清楚我需要什么。在这里我尝试使用接口(interface),但后来我发现我无法将接口(interface)对象传递给广播接收器构造函数。

我的解决方案有界面但不工作:

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

在 fragment 类中,我实现了带有方法的接口(interface)、注册接收器等......

 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 执行此操作,它就可以工作。您无需在 list 中声明此 BroadcastReceiver

您得到 Exception: Unable to instantiate receiver no empty constructor. 的原因是因为 Android 正在尝试实例化 BroadcastReceiver。 (无论出于何种原因)。

关于java - 来自广播接收器的通知 fragment 或 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27846173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com