Android Genny运动中测试位置的变化

Android Genny运动中测试位置的变化,android,genymotion,Android,Genymotion,在genny运动中测试位置如何从一个位置变化到另一个位置 在这里,我把我的代码张贴在onLocationChanged上从未调用过的地方 public class RouteMapActivity extends AppCompatActivity implements LocationListener, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFail

在genny运动中测试位置如何从一个位置变化到另一个位置 在这里,我把我的代码张贴在
onLocationChanged
上从未调用过的地方

public class RouteMapActivity extends AppCompatActivity implements  
   LocationListener, OnMapReadyCallback, 

GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener 


{

private static final long MIN_DISTANCE_FOR_UPDATE = 10;

private static final int LOCATION_SETTINGS_REQUEST_CODE = 1;

private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;

private static final LatLng latlngHiLiteMall = new LatLng(11.248823, 75.833760);

private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;


private boolean mRequestingLocationUpdates = false;

private LocationRequest mLocationRequest;

private static int UPDATE_INTERVAL = 10000;

private static int FATEST_INTERVAL = 5000; /


private static int DISPLACEMENT = 10; 



boolean isGPSTrackingEnabled = false;
LatLng latLngMyLocation = null;
AlertDialog alertDlg;
GoogleApiClient googleApiClient;
LocationSettingsRequest.Builder builder;
double myLocLat, myLocLong;
LocationManager locationManager;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
ConnectionInfo connectionInfo;
private Location mLastLocation;
private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_route_map);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    getSupportActionBar().setHomeButtonEnabled(true);

    connectionInfo = new ConnectionInfo(this);

    Log.e("Rout Map.....","on Create....!");

    if (checkPlayServices()) {

        buildGoogleApiClient();

        createLocationRequest();

    }

    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    setUpMapIfNeeded();

}

private void createLocationRequest() {

    mLocationRequest = new LocationRequest();

    mLocationRequest.setInterval(UPDATE_INTERVAL);

    mLocationRequest.setFastestInterval(FATEST_INTERVAL);

    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}

private boolean checkPlayServices() {

    int resultCode = GooglePlayServicesUtil

            .isGooglePlayServicesAvailable(this);

    if (resultCode != ConnectionResult.SUCCESS) {

        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {

            GooglePlayServicesUtil.getErrorDialog(resultCode, this,

                    PLAY_SERVICES_RESOLUTION_REQUEST).show();

        } else {

            Toast.makeText(getApplicationContext(),
                    "This device is not supported.", Toast.LENGTH_LONG)
                    .show();

            finish();
        }
        return false;
    }
    return true;
}


@Override
protected void onStart() {
    super.onStart();

    googleApiClient.connect();
}

@Override
protected void onStop() {
    super.onStop();

    if (googleApiClient.isConnected()) {

        googleApiClient.disconnect();
    }
}

protected synchronized void buildGoogleApiClient() {

    googleApiClient = new GoogleApiClient.Builder(this)

            .addConnectionCallbacks(this)

            .addOnConnectionFailedListener(this)

            .addApi(LocationServices.API)
            .build();
}


@Override
protected void onResume() {

    super.onResume();

    checkPlayServices();

    isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

    isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if (!isGPSEnabled)

        showAlertDialog();

    if (googleApiClient.isConnected()) {

        startLocationUpdates();
    }
}

@Override
protected void onPause() {

    super.onPause();

    stopLocationUpdates();
}

private void togglePeriodicLocationUpdates() {

    if (!mRequestingLocationUpdates) {

        mRequestingLocationUpdates = true;

        startLocationUpdates();

        Log.d("TAG", "Periodic location updates started!");

    } else {


        mRequestingLocationUpdates = false;

        stopLocationUpdates();

        Log.d("TAG", "Periodic location updates stopped!");
    }
}

private void stopLocationUpdates() {

    LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}

protected void startLocationUpdates() {

    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, mLocationRequest, this);
}

private void setUpMapIfNeeded() {

    if (mMap != null) {

        return;
    }
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);

    mapFragment.getMapAsync(this);

    if (mMap == null) {

        return;
    }
}

@Override
public void onMapReady(GoogleMap googleMap) {

    mMap = googleMap;

    mMap.setMyLocationEnabled(true);

    mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {

        @Override
        public boolean onMyLocationButtonClick() {

            if (!isGPSEnabled) {

                Toast.makeText(RouteMapActivity.this, "GPS is disabled!", Toast.LENGTH_SHORT).show();
            }

            return false;
        }
    });

    // Add a marker in Sydney and move the camera
    mMap.addMarker(new MarkerOptions().position(latlngHiLiteMall).title("HiLite Mall"));

    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlngHiLiteMall, 12));


    //getMyCurrentLocation();
    getMyLocation();

}

private void getMyLocation() {

    mLastLocation = LocationServices.FusedLocationApi
            .getLastLocation(googleApiClient);


    if (mLastLocation != null) {

        Log.d("NOT NULL", ">>>>>>>>>>>");

        if (alertDlg != null && alertDlg.isShowing())

            alertDlg.dismiss();

        myLocLat = mLastLocation.getLatitude();

        myLocLong = mLastLocation.getLongitude();


        if (connectionInfo.isConnectingToInternet()) {

            latLngMyLocation = new LatLng(myLocLat, myLocLong);

            mMap.addMarker(new MarkerOptions().position(latLngMyLocation).title("My Loc"));

            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngMyLocation, 12));

            new MapTask().execute();

        } else {

            Toast.makeText(this, "Enable Internet", Toast.LENGTH_SHORT).show();
        }

        Toast.makeText(RouteMapActivity.this, "G--" + myLocLat, Toast.LENGTH_SHORT).show();

    } else {

        Toast.makeText(RouteMapActivity.this, "Couldn't get the location. Make sure location is enabled on the device", Toast.LENGTH_SHORT).show();
    }
}



private Location getLastKnownLocation() {


    List<String> providers = locationManager.getProviders(true);

    Location bestLocation = null;

    for (String provider : providers) {

        Location l = locationManager.getLastKnownLocation(provider);

        Log.d("last known location", "" + provider + " " + l);

        if (l == null) {

            continue;
        }
        if (bestLocation == null
                || l.getAccuracy() < bestLocation.getAccuracy())
        {
            Log.d("last known location", "" + provider + " " + l);

            bestLocation = l;
        }
    }
    if (bestLocation == null) {

        return null;
    }

    return bestLocation;
}


private void showAlertDialog() {

    AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

    alertDialog.setTitle("Use Location?");


    alertDialog.setMessage("Helps for find the route to HiLite Mall.");


    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {

            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);

            startActivityForResult(intent, LOCATION_SETTINGS_REQUEST_CODE);
        }
    });

    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {

            dialog.cancel();
        }
    });

    alertDlg = alertDialog.create();

    alertDlg.show();

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == LOCATION_SETTINGS_REQUEST_CODE) {

        Log.d("TAG", "Activity Result");

        getMyLocation();

    }

}



@Override
public void onConnected(Bundle connectionHint) {

    getMyLocation();

    if (mRequestingLocationUpdates) {
        startLocationUpdates();
    }
}

@Override
public void onConnectionFailed(ConnectionResult result) {

    Log.i("API CLIENT", "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}


@Override
public void onConnectionSuspended(int cause) {

    Log.i("API CLIENT", "Connection suspended");

    googleApiClient.connect();
}

@Override
public void onLocationChanged(Location location) {
    Log.e("Location Changed.....","Location changed....!");

    mLastLocation = location;
    // Displaying the new location on UI
    getMyLocation();
}





private class MapTask extends AsyncTask<Void, Void, PolylineOptions> {

    @Override
    protected PolylineOptions doInBackground(Void... params) {

        GMapV2Direction md = new GMapV2Direction();

        Document doc = md.getDocument(latLngMyLocation, latlngHiLiteMall, GMapV2Direction.MODE_DRIVING);

        ArrayList<LatLng> directionPoint = md.getDirection(doc);

        PolylineOptions rectLine = new PolylineOptions().width(5).color(Color.RED);


        for (int i = 0; i < directionPoint.size(); i++) {

            rectLine.add(directionPoint.get(i));
        }
        return rectLine;
    }

    @Override
    protected void onPostExecute(PolylineOptions rectLine) {

        mMap.addPolyline(rectLine);

    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    switch (id) {

        case android.R.id.home:

            this.finish();

            return true;



    }
    return super.onOptionsItemSelected(item);
}
}
公共类RouteMapActivity扩展了AppCompatActivity实现
LocationListener,OnMapReadyCallback,
GoogleAppClient.ConnectionCallbacks,GoogleAppClient.OnConnectionFailedListener
{
私有静态最终长最小距离,用于更新=10;
私有静态最终整数位置\设置\请求\代码=1;
用于更新的私有静态最终长最小时间=1000*60*2;
专用静态最终LatLng latlngHiLiteMall=新LatLng(11.248823,75.833760);
专用最终静态整数播放服务解析请求=1000;
私有布尔值mRequestingLocationUpdates=false;
私人位置请求mLocationRequest;
私有静态int更新间隔=10000;
专用静态整数测试间隔=5000/
私有静态int位移=10;
布尔值IsGPStrackEnabled=false;
LatLng latLngMyLocation=null;
AlertDialog alertDlg;
GoogleapClient GoogleapClient;
位置设置请求生成器;
双myLocLat,myLocLong;
地点经理地点经理;
布尔值isGPSEnabled=false;
布尔值isNetworkEnabled=false;
ConnectionInfo ConnectionInfo;
私人场所;
私有谷歌地图;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u route\u map);
Toolbar Toolbar=(Toolbar)findViewById(R.id.Toolbar);
设置支持操作栏(工具栏);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
connectionInfo=新的connectionInfo(此);
Log.e(“路由映射…”,“创建时…”);
如果(checkPlayServices()){
buildGoogleAppClient();
createLocationRequest();
}
locationManager=(locationManager)getSystemService(位置服务);
setupmapifneed();
}
私有void createLocationRequest(){
mlLocationRequest=新位置请求();
mLocationRequest.setInterval(更新间隔);
mLocationRequest.SetFastTestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(位置请求.优先级高精度);
M定位请求。设置最小位移(位移);
}
私有布尔值checkPlayServices(){
int resultCode=GooglePlayServicesUtil
.isGooglePlayServicesAvailable(此);
if(resultCode!=ConnectionResult.SUCCESS){
if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)){
GooglePlayServicesUtil.getErrorDialog(结果代码,此,
播放服务解决方案请求)。显示();
}否则{
Toast.makeText(getApplicationContext(),
“不支持此设备。”,Toast.LENGTH\u LONG)
.show();
完成();
}
返回false;
}
返回true;
}
@凌驾
受保护的void onStart(){
super.onStart();
googleApiClient.connect();
}
@凌驾
受保护的void onStop(){
super.onStop();
if(googleApiClient.isConnected()){
googleApiClient.disconnect();
}
}
受保护的同步无效BuildGoogleAppClient(){
GoogleapClient=新的GoogleapClient.Builder(此)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.addApi(LocationServices.API)
.build();
}
@凌驾
受保护的void onResume(){
super.onResume();
checkPlayServices();
isGPSEnabled=locationManager.isProviderEnabled(locationManager.GPS\U提供程序);
isNetworkEnabled=locationManager.isProviderEnabled(locationManager.NETWORK\u提供程序);
如果(!isGPSEnabled)
showAlertDialog();
if(googleApiClient.isConnected()){
startLocationUpdates();
}
}
@凌驾
受保护的void onPause(){
super.onPause();
stopLocationUpdates();
}
private void togglePeriodicLocationUpdates(){
如果(!mrequestingLocationUpdate){
mRequestingLocationUpdates=true;
startLocationUpdates();
Log.d(“标记”,“定期位置更新已开始!”);
}否则{
mRequestingLocationUpdates=false;
stopLocationUpdates();
Log.d(“标记”,“定期位置更新已停止!”);
}
}
私有void stopLocationUpdates(){
LocationServices.FusedLocationApi.RemovelocationUpdate(GoogleAppClient,this);
}
受保护的void startLocationUpdates(){
LocationServices.FusedLocationApi.RequestLocationUpdate(GoogleAppClient、MLLocationRequest、this);
}
私有void setUpMapIfNeeded(){
如果(mMap!=null){
返回;
}
SupportMapFragment mapFragment=(SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map);
getMapAsync(这个);
如果(mMap==null){
返回;
}
}
@凌驾
4月1日公开作废(谷歌地图谷歌地图){
mMap=谷歌地图;
mMap.setMyLocationEnabled(真);
mMap.setOnMyLocationButtonClickListener(新的GoogleMap.OnMyLocationButtonClickListener(){
@凌驾
公共布尔onMyLocationButtonClick(){
如果(!isGPSEnabled){
Toast.makeText(RouteMapActivity.this,“GPS已禁用!”,Toast.LENGTH\u SHORT.show();
}
返回false;
}
});
//在Sydney添加一个标记并移动相机
mMap.addMarker(新MarkerOptions().position(latlngHiLiteMall).title(“HiLite购物中心”);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlngHiLiteMall,12));
//getMyCurrentLocation();
getMyLocation();
}
私有void getMyLocation(){
mLastLocation=LocationServices.FusedLocationApi
.getLastLocation(GoogleapClient);
如果(mLastLocation!=null){
Log.d(“非空”,“>>>>>>”);
if(alertDlg!=null&&alertDlg.isShowing())
alertDlg.discouse();
myLocLat=mLastLocation.getLatitude();
myLocLong=mLastLocation.getLongitude();
if(c)