我想查找应用程序在后台运行时的当前位置
我有以下代码,用于在后台运行服务中查找当前位置。但它不起作用。
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 */
}
答案 0 :(得分:1)
我认为您需要使用GPS进行当前纬度和经度值。
点击此链接.. Click link
我已经尝试过并在Android手机上进行测试..它正在工作。
注意: 模拟器我们没有得到Curent GPS位置..您必须并且应该在手机中安装您的应用程序.. 首先,你尝试使用手机上的GPS,它会工作。
度过愉快的一天。