来自MainActivity.java的Android Split GPS跟踪文件

时间:2017-09-28 07:45:42

标签: java android gps

我无法弄清楚如何将这个分成2个文件。我希望在 MainActivity.java 时需要一个文件 GPSTracking.java 来调用。

这是我必须拆分的文件

public class MainActivity extends AppCompatActivity implements LocationListener {


final String TAG = "GPS";
private final static int ALL_PERMISSIONS_RESULT = 101;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60;

TextView tvLatitude, tvLongitude;
LocationManager locationManager;
Location loc;
ArrayList<String> permissions = new ArrayList<>();
ArrayList<String> permissionsToRequest;
ArrayList<String> permissionsRejected = new ArrayList<>();
boolean isGPS = false;
boolean isNetwork = false;
boolean canGetLocation = true;

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

    tvLatitude = (TextView) findViewById(R.id.tvLatitude);
    tvLongitude = (TextView) findViewById(R.id.tvLongitude);

    locationManager = (LocationManager) getSystemService(Service.LOCATION_SERVICE);
    isGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    isNetwork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    permissionsToRequest = findUnAskedPermissions(permissions);

    if (!isGPS && !isNetwork) {
        Log.d(TAG, "Connection off");
        showSettingsAlert();
        getLastLocation();
    } else {
        Log.d(TAG, "Connection on");
        // check permissions
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (permissionsToRequest.size() > 0) {
                requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]),
                        ALL_PERMISSIONS_RESULT);
                Log.d(TAG, "Permission requests");
                canGetLocation = false;
            }
        }

        // get location
        getLocation();
    }
}

@Override
public void onLocationChanged(Location location) {
    Log.d(TAG, "onLocationChanged");
    updateUI(location);
}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}

@Override
public void onProviderEnabled(String s) {
    getLocation();
}

@Override
public void onProviderDisabled(String s) {
    if (locationManager != null) {
        locationManager.removeUpdates(this);
    }
}

private void getLocation() {
    try {
        if (canGetLocation) {
            Log.d(TAG, "Can get location");
            if (isGPS) {
                // from GPS
                Log.d(TAG, "GPS on");
                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                if (locationManager != null) {
                    loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (loc != null)
                        updateUI(loc);
                }
            } else if (isNetwork) {
                // from Network Provider
                Log.d(TAG, "NETWORK_PROVIDER on");
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                if (locationManager != null) {
                    loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (loc != null)
                        updateUI(loc);
                }
            } else {
                loc.setLatitude(0);
                loc.setLongitude(0);
                updateUI(loc);
            }
        } else {
            Log.d(TAG, "Can't get location");
        }
    } catch (SecurityException e) {
        e.printStackTrace();
    }
}

private void getLastLocation() {
    try {
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);
        Log.d(TAG, provider);
        Log.d(TAG, location == null ? "NO LastLocation" : location.toString());
    } catch (SecurityException e) {
        e.printStackTrace();
    }
}

private ArrayList findUnAskedPermissions(ArrayList<String> wanted) {
    ArrayList result = new ArrayList();

    for (String perm : wanted) {
        if (!hasPermission(perm)) {
            result.add(perm);
        }
    }

    return result;
}

private boolean hasPermission(String permission) {
    if (canAskPermission()) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);
        }
    }
    return true;
}

private boolean canAskPermission() {
    return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
}

@TargetApi(Build.VERSION_CODES.M)
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case ALL_PERMISSIONS_RESULT:
            Log.d(TAG, "onRequestPermissionsResult");
            for (String perms : permissionsToRequest) {
                if (!hasPermission(perms)) {
                    permissionsRejected.add(perms);
                }
            }

            if (permissionsRejected.size() > 0) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (shouldShowRequestPermissionRationale(permissionsRejected.get(0))) {
                        showMessageOKCancel("These permissions are mandatory for the application. Please allow access.",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                            requestPermissions(permissionsRejected.toArray(
                                                    new String[permissionsRejected.size()]), ALL_PERMISSIONS_RESULT);
                                        }
                                    }
                                });
                        return;
                    }
                }
            } else {
                Log.d(TAG, "No rejected permissions.");
                canGetLocation = true;
                getLocation();
            }
            break;
    }
}

public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
    alertDialog.setTitle("GPS is not Enabled!");
    alertDialog.setMessage("Do you want to turn on GPS?");
    alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }
    });

    alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    alertDialog.show();
}

private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
    new AlertDialog.Builder(MainActivity.this)
            .setMessage(message)
            .setPositiveButton("OK", okListener)
            .setNegativeButton("Cancel", null)
            .create()
            .show();
}

public String formatValue(double d){
    String dStr = String.valueOf(d);
    String value = dStr.matches("\\d+\\.\\d*[1-9]\\d*") ? dStr : dStr.substring(0,dStr.indexOf("."));
    return value;
}



private void updateUI(Location loc) {
    Log.d(TAG, "updateUI");
    double latitude = loc.getLatitude();
    double longitude = loc.getLongitude();

    tvLatitude.setText(formatValue(latitude));
    tvLongitude.setText(formatValue(longitude));

}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (locationManager != null) {
        locationManager.removeUpdates(this);
    }
    android.os.Process.killProcess(android.os.Process.myPid());
    super.onDestroy();
}


}

我需要两个文件: MainActivity.java GPSTracking.java ,但我真的无法弄清楚如何将其拆分为这两个文件。谢谢大家!

1 个答案:

答案 0 :(得分:0)

创建一个新的GpsTracking.java并实现以下接口。

 1. LocationListener (`import com.google.android.gms.location.LocationListener`)
 2. GoogleApiClient.ConnectionCallbacks
 3. GoogleApiClient.OnConnectionFailedListener

然后使用GoogleApiClient完成剩下的工作。 不要忘记使用LocationManagerFusedLocationApi

但我建议,你应该在同一个类中实现它。除非你想重复使用它。 但是,它仍然降低了代码和算法的复杂性。