簡體   English   中英

如何使流程自動化?

[英]How can I make automatic a process?

我制作了一個GPS教程,您可以按一下按鈕獲取位置,但是現在我想自動進行此過程,我嘗試在onCreate方法上調用它,但只能運行一次。 這就是我嘗試的:

GPS等級

public class GPS implements LocationListener{

private final Context mContext;

//flag for GPS status
boolean isGPSEnable = false;

// Flag for network status
boolean isNetworkEnable = false;

// flag for GPS status
boolean canGetLocation = false;

Location location;  //location
double latitude;     //latitude
double longitude;   //longitude

// the minimum distances to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // Minimun distance 10 meters

// The minimum time between updates in millisenconds
private static final long MIN_TIME_BTW_UPDATES = 1000 * 60 * 1; // 1 MINUTE

// Declaring a Location Manager
protected LocationManager locationManager;

public GPS(Context context){
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(Context.LOCATION_SERVICE);

        //getting GPS status
    isGPSEnable = locationManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);

        //getting network status
        isNetworkEnable = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if(!isGPSEnable && !isNetworkEnable){
            // no network provider is enable
        }
        else {
            this.canGetLocation = true;
            if(isNetworkEnable){
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BTW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, (LocationListener) this);
                Log.d("Network", "Network");
                if(locationManager != null){
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if(location != null){
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enable get lat/long using GPS Services
            if(isGPSEnable){
                if(location == null){
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BTW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS ENABLE", "GPS Enabled");
                    if(locationManager != null){
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null){
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }
    }catch (Exception e){
        e.printStackTrace();
    }
    return location;
}

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 */

public void stopUsingGPS(){
    if (locationManager != null){
        locationManager.removeUpdates((LocationListener) GPS.this);
    }
}

/**
 * function to get latitude
 */
public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }
    //return latitude
    return latitude;
}

public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }
    //return longitude
    return  longitude;
}

/**
 * Function to check GPS/wifi enable
 * @return boolean
 */
public  boolean canGetLocation(){
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will launch Settings Options
 */

public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle(mContext.getString(R.string.AlertDialog_Tittle));

    // Setting Dialog Message
    alertDialog.setMessage(mContext.getString(R.string.dialog_message));

    // On pressing Setting button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        }
    });

    // On pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });
}

@Override
public void onLocationChanged(Location location){

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

}

和主要活動類別:

public class MainActivity extends ActionBarActivity {

private EditText edTLatitud;
private EditText edTLongitud;
private EditText edTCompass;
private EditText edTDirecc;
private SensorManager sensorManager;
private Sensor compassSensor;

// GPS class
GPS gps;

// Compass class
Compass compass;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gpsactivity);

    edTCompass = (EditText)this.findViewById(R.id.edTxtBrujula);
    edTDirecc = (EditText)this.findViewById(R.id.edTxtBrujdireccion);
    edTLatitud = (EditText)this.findViewById(R.id.edTxtLatitud);
    edTLongitud = (EditText)this.findViewById(R.id.edTxtLongitud);

    sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
    compassSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

    gps = new GPS(MainActivity.this);

    // Check if GPS is enable
    if(gps.canGetLocation()){

        double latitude = gps.getLatitude();
        double longitude = gps.getLongitude();

        // Print on the screen the coordinates
        UpdateGPSonScreen(latitude, longitude);
    }
    else {
        // can't get location
        // GPS or network is not enable
        // Ask user to enable GPS/network in settings
        gps.showSettingsAlert();
    }
}

// Show the Latitude and longitude of the GPS on the application
public  void UpdateGPSonScreen(double latitude, double longitude)
{
    try{
        edTLatitud.setText(String.valueOf(latitude));
        edTLongitud.setText(String.valueOf(longitude));
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

提前致謝...

您是否要間歇地使用用戶位置信息更新EditText? 如果是這樣,您可以創建一個線程,該線程每隔一段時間調用一個檢索位置數據的函數。

如果除MainActivity之外的其他任何地方都未使用GPS類,則將其作為您的Activity的內部類,或在Activity類本身中實現ImplementLocationListener,以在onLocationChanged方法內更新TextViews。

locationManger空值檢查放在任何地方之前,在多次使用后檢查空值是沒有意義的。

你的班級結構應該像

 public class MainActivity extends ActionBarActivity{

   // Define your text views to use them globally

   @Override
   protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.gpsactivity);

    //find all your views

   }

   class GPS implements LocationListener{

    //copy all your code here with required correction

      @Override
      public void onLocationChanged(Location location){

       //get your latitude and longitude from location Object
       // call same method to update your view

      }
   }

 }

我只在stackoverflow編輯器中編寫了整個代碼,因此,如果發現任何語法錯誤,請進行更正。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM