我有一个 GPSTracker
类,它扩展服务实现 LocationListener
。
并且 GPSTracker
也覆盖了 onLocationChanged
方法。
在我的 MainActivity
中,我创建了一个 GPSTracker
实例,并使用我在 GPSTracker
类中声明的自定义方法来获取纬度/经度。
当 GPSTracker
的 onLocationChanged
被触发时,如何让我的 MainActivity
得到通知?
GPSTracker
类
public class GPSTracker extends Service implements LocationListener {
...
Location location; // location
double latitude; // latitude
double longitude; // longitude
...
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
...
return location;
}
public void stopUsingGPS(){
...
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert(){
...
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
// do some stuff
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
最佳答案
我看到两种通知 MainActivity 的方法:
首先,您可以创建一个在 MainActivity 上实现并由 GPSTracker 触发的监听器。
其次,可以看看BroadcastReceiver。只需在您的主要 Activity 中添加 BroadcastReceiver 即可。在您的方法 OnLocationChanged 上,您只需创建一个新的 Intent :
Intent intent = new Intent("LocationChanged");
intent.setType("text/plain");
sendBroadcast(intent);
我认为第一个解决方案不是最简单但更好。
关于android - 从 Activity 中监听 LocationChanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20283534/