【发布时间】:2013-09-26 02:44:26
【问题描述】:
我有一个获取用户位置的类。
如果 GPS 关闭,我将其打开并显示位置,但它不起作用。
这是类:
public class UseGPS implements Runnable{
Activity activity;
Context context;
private ProgressDialog pd;
LocationManager mLocationManager;
Location mLocation;
MyLocationListener mLocationListener;
Location currentLocation = null;
public UseGPS(Activity Activity, Context Context){
this.activity = Activity;
this.context = Context;
}
public void getMyPos(){
DialogInterface.OnCancelListener dialogCancel = new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
Toast.makeText(activity,"no gps signal",Toast.LENGTH_LONG).show();
handler.sendEmptyMessage(0);
}
};
pd = ProgressDialog.show(activity,context.getString(R.string.looking_for), context.getString(R.string.gps_signal), true, true, dialogCancel);
writeSignalGPS();
}
private void setCurrentLocation(Location loc) {
currentLocation = loc;
}
private void writeSignalGPS() {
Thread thread = new Thread(this);
thread.start();
}
public void run() {
mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
Looper.prepare();
mLocationListener = new MyLocationListener();
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
Looper.loop();
Looper.myLooper().quit();
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
pd.dismiss();
mLocationManager.removeUpdates(mLocationListener);
if (currentLocation!=null) {
Toast.makeText(activity,currentLocation.getLatitude(),Toast.LENGTH_LONG).show();
Toast.makeText(activity,currentLocation.getLongitude(),Toast.LENGTH_LONG).show();
}
}
};
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {
if (loc != null) {
setCurrentLocation(loc);
handler.sendEmptyMessage(0);
}
}
@Override
public void onProviderDisabled(String provider) {
/*turn on GPS*/
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
context.sendBroadcast(intent);
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
打开 GPS 时代码可以工作,但不能打开 gps。
我能做什么?
【问题讨论】:
-
如果在“设置”中禁用了 GPS,则无法通过代码将其打开。早期版本的 Android 确实允许它,但后来(发布 Gingerbread?)版本禁止它。
-
要求用户开启
-
您无法以编程方式打开 GPS。这个问题已经出现过很多次了。请在发布问题之前先进行搜索。
-
onProviderDisabled()中的 script-kiddie hack 不适用于大多数 Android 设备。