等待函数运行然后启动活动

时间:2013-03-29 12:18:21

标签: android android-activity

当用户按下开始按钮时,会运行检查以查看GPS是否已启用然后开始活动.checkGPS使用alertmanager。

case R.id.startbtn:
        checkGPS();
        Intent gpslocation=new Intent(this,selection.class);
        startActivity(gpslocation);
        break;

如何等待用户启用GPS然后开始活动?

1 个答案:

答案 0 :(得分:1)

1)在onCreate()方法中,在您的活动中注册LocationListener

   // get location manager
   LocationManager lManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
   Button btnStart = (Button)findViewById(R.id.btnStart);
   btnStart.setOnClickListener(new OnClickListener() {
       @Override
       public void onClick(View v) {
            lManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, YourActivity.this);
       }
   });

2)您的活动应实施LocationListener

   public class YourActivity extends Activity implements LocationListener {

3)覆盖LocationListener

的方法

@覆盖 public void onLocationChanged(Location location){      //当位置发生变化时      Log.d(TAG,“位置已更改。”);
}

@Override
public void onProviderDisabled(String provider) {
     // when the source (GSP or GSM network) are disabled
     Log.d(TAG, "the source "+provider+" has been disabled");
}

@Override
public void onProviderEnabled(String provider) {
     Log.i(TAG, "the source "+provider+" has been enabled");
     //here you should test if the provider enabled is GPS , if yes , then launch your GPSActivity
     if(provider.equals("gps") {
           Intent gpslocation=new Intent(this,selection.class);
           startActivity(gpslocation);
     }
     else {
           //launch your alert dialog here
     }
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
     Log.i(TAG, "source status "+provider+" has been changed to : "+status);
}