如果禁用GPS,请关闭应用程序

时间:2012-05-11 02:56:52

标签: android gps location

我有申请从gps获取位置
但如果GPS禁用我的应用程序,请关闭力量 在模拟器中它没有错误,但如果在设备中运行它会强制关闭
我怎样才能做到这一点?? 这是我的代码:

public class Track extends Activity implements LocationListener{
String curTime;
double lat;
double lng;
double alt;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final LocationManager locationManager;
    String context = Context.LOCATION_SERVICE;
    locationManager = (LocationManager)getSystemService(context);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    final String provider = locationManager.getBestProvider(criteria, true);
    Dbhelper helper = new Dbhelper(this);
    final SQLiteDatabase db = helper.getWritableDatabase();
    updateWithNewLocation(null);
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask(){
        @Override
        public void run(){
            db.isOpen();
            db.execSQL("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " +
                    "('"+lng+"','"+lat+"','"+alt+"','"+curTime+"')");
            //db.close();
        }
    }, 10*60*1000, 10*60*1000);
    locationManager.requestLocationUpdates(provider, (10*60*1000), 10,
                                           locationListener);
    PackageManager manager = this.getPackageManager();
    PackageInfo info = null;
    try {
        info = manager.getPackageInfo(this.getPackageName(), 0);
    } catch (NameNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Toast.makeText(this,
      "PackageName = " + info.packageName + "\nVersionCode = "
        + info.versionCode + "\nVersionName = "
        + info.versionName + "\nPermissions = "+info.permissions, Toast.LENGTH_SHORT).show();
    System.out.println("PackageName = " + info.packageName + "\nVersionCode = "
        + info.versionCode + "\nVersionName = "
        + info.versionName + "\nPermissions = "+info.permissions);
}
private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
      updateWithNewLocation(location);
    }

    public void onProviderDisabled(String provider){
      updateWithNewLocation(null);
    }

    public void onProviderEnabled(String provider){ }
    public void onStatusChanged(String provider, int status, 
                                Bundle extras){ }
  };
  public void updateWithNewLocation(Location location) {


        if (location != null) {
            Dbhelper helper = new Dbhelper(this);
            final SQLiteDatabase db = helper.getWritableDatabase();
            long time = System.currentTimeMillis();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
            curTime = df.format(time);
            lat = location.getLatitude();
            lng = location.getLongitude();
            alt = location.getAltitude();
            System.out.println(lat);
            System.out.println(lng);
            System.out.println(alt);
            /*db.execSQL("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " +
            "('"+lng+"','"+lat+"','"+alt+"','"+curTime+"')");
            db.close();*/
            /*Timer timer = new Timer();
            timer.schedule(new TimerTask(){
                @Override
                public void run(){
                    db.execSQL("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " +
                            "('"+lng+"','"+lat+"','"+alt+"','"+curTime+"')");
                    db.close();
                }
            }, 10*60*1000, 10*60*1000);*/

          } 
       }
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub

}
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

}
}

请给我一个解决方案..谢谢你的反馈:)

3 个答案:

答案 0 :(得分:3)

如果您想在应用中自动启用GPS,我担心除了提示用户之外别无他法。

通过修改LocationListener中的onProviderDisabled()方法,您可以轻松实现这一目标。想法是打开一个对话框,要求用户打开GPS:

public void onProviderDisabled(String arg0) 
    {
        showDialog(CHOICE_GPS_ENABLE);          
    }

添加您的活动:

    protected final static int CHOICE_GPS_ENABLE = 1; //or any other number

@Override
protected Dialog onCreateDialog(int id)
{
    Dialog dialog = null;
    switch (id)
    {
        case CHOICE_GPS_ENABLE:
            dialog = createGPSEnableDialog();
            break;

        default:
            dialog = super.onCreateDialog(id);
            break;
    }

    return dialog;
}

    protected Dialog createGPSEnableDialog()
{
    Dialog toReturnGPS;

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("You don't have GPS enabled. Go to Settings and enable GPS?");

    builder.setTitle("GPS failed");

    builder.setPositiveButton("Yes, enable GPS",
            new DialogInterface.OnClickListener() 
                {
                    public void onClick(DialogInterface dialog, int which) 
                        {
                          Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                          startActivity(intent);
                        }
                });

    builder.setNegativeButton("No, quit application",
            new DialogInterface.OnClickListener() 
                {
                    public void onClick(DialogInterface dialog, int which) 
                        {
                            onDestroy();
                        }
                });

    toReturnGPS = builder.create();
    return toReturnGPS;
}

希望它有所帮助。

答案 1 :(得分:0)

  

如果我的应用程序正在运行,我希望GPS自动开启   我怎么能这样做?

除了提示用户打开它之外,我认为你不能做任何事情。所以我担心你无法按照自己的意愿使应用程序工作。

答案 2 :(得分:0)

使用

Location locationtest;
     public void onLocationChanged(Location location) {
          locationtest=location;
          updateWithNewLocation(locationtest);
        }

        public void onProviderDisabled(String provider){
              locationtest= null;
              updateWithNewLocation(locationtest);
            }

而不是

 public void onProviderDisabled(String provider){
      updateWithNewLocation(null);
    }