gpt4 book ai didi

android - 我无法配置 Intent 和 BroadcastReceiver

转载 作者:太空狗 更新时间:2023-10-29 12:50:22 25 4
gpt4 key购买 nike

我想从“class gps_Listener”创建“Intent”并在“class LocationChangedReceiver”中发送参数

我的类(class) gps_Listener

public class gps_Listener implements LocationListener {

public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
send("I found the location");

}

public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub

}

public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub

}

public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub

}

public void send(String str) {
Intent intent = new Intent("logGPS");
intent.putExtra("Message", str);
sendBroadcast(intent); //- without context does not work

}


}

和类 LocationChangedReceiver

public class LocationChangedReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub

}

}

我不知道该怎么做,因为你可以看到没有“上下文”

最佳答案

您可以在创建上下文时将上下文传递给监听器。所以你可以在你的发送方法中使用它:

public class gps_Listener implements LocationListener {
private Context context;

public gps_Listener(Context context) {
this.context = context;
}

...

public void send(String str) {
Intent intent = new Intent("com.your.package.YOUR_ACTION");
intent.putExtra("Message", str);
context.sendBroadcast(intent);
}
}

以这种方式创建它:

gps_Listener myListener = new gps_Listener(yourContext);
LocationManager myManager = (LocationManager)getSystemService(LOCATION_SERVICE);
myManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, myListener);

请记住在 list 中注册您的广播接收器(您也可以动态取消/注册):

<receiver android:name=".receivers.LocationChangedReceiver" android:enabled="true">
<intent-filter>
<action android:name="com.your.package.YOUR_ACTION"></action>
</intent-filter>
</receiver>

关于android - 我无法配置 Intent 和 BroadcastReceiver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12703433/

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