Finding current Location when the application is r

2019-08-02 06:38发布

问题:

I want to find out current location when the Application is running in background

I Have below code for finding current location in background running services. But its not working.

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
public class MyService extends Service {
private static LocationManager mlocManager;
private static final String TAG = "MyService";


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

@Override
public void onCreate() {
    Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onCreate");

}

@Override
public void onDestroy() {
    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onDestroy");

}

@Override
public void onStart(Intent intent, int startid) {
    Toast.makeText(this, "start My Service Started", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onStart");
     mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

    LocationListener mlocListener = new MyLocationListener();
    //Location newloc= new Location();


    mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);

    Toast.makeText(this, "hiiiits created", Toast.LENGTH_LONG).show();

}
/* Class My Location Listener */

public class MyLocationListener implements LocationListener

{

@Override

public void onLocationChanged(Location loc)

{
    Log.d(TAG, "onlocationchnage");
loc.getLatitude();

loc.getLongitude();

String Text ="My current location is: " +

"Latitud = " + loc.getLatitude() +

"Longitud = " + loc.getLongitude();

Toast.makeText( getApplicationContext(),

Text,

Toast.LENGTH_SHORT).show();

}

@Override

public void onProviderDisabled(String provider)

{

Toast.makeText( getApplicationContext(),

"Gps Disabled",

Toast.LENGTH_SHORT ).show();

}

@Override

public void onProviderEnabled(String provider)

{

Toast.makeText( getApplicationContext(),

"Gps Enabled",

Toast.LENGTH_SHORT).show();

}

@Override

public void onStatusChanged(String provider, int status, Bundle extras)

{

}

}/* End of Class MyLocationListener */
}

回答1:

I think you need Current Latitude and Longitude values using GPS..

follow this link.. Click link

I already tried it and test it in android mobile phone.. Its working.

Note : emulator we are not get the Curent GPS location.. You must and should install your application in phone.. First you ON the GPS in mobile phone after try it, it will work.

have a nice day.



标签: android gps