简体   繁体   English

如何使用 android 应用程序在后台跟踪位置?

[英]How to track location in the background using an android app?

Im a complete beginner in this and using android studio to make a GPS tracking app for a project.我是一个完整的初学者,并使用 android 工作室为项目制作 GPS 跟踪应用程序。 I need the app to be able to track the user's location even when the app is closed.即使应用程序关闭,我也需要该应用程序能够跟踪用户的位置。 Something like how the Uber app tracks your location even if the app isn't open.类似于 Uber 应用程序如何在应用程序未打开的情况下跟踪您的位置。 How do i do something like that?我该怎么做这样的事情?

ADD THIS IN YOUR MANIFEST:在您的清单中添加:

   <uses-permission android:name="android.permission.INTERNET"></uses-permission>
   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>

Declare service in the manifest在清单中声明服务

  <service android:name=".LocationService"></service>

In your activity do following steps在您的活动中执行以下步骤

   private static final int REQUEST_PERMISSIONS = 100;
   Double latitude,longitude;
   Geocoder geocoder;
   boolean isPermissionAllowed;

Oncreate:创建:

    geocoder = new Geocoder(this, Locale.getDefault());
    Location_permission();

   if (isPermissionAllowed) {
    Intent intent = new Intent(getApplicationContext(), LocationService.class);
    startService(intent);
    }


  private void Location_permission() {
    if ((ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {

        if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION))) {


        } else {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION

                    },
                    REQUEST_PERMISSIONS);

        }
    } else {
        isPermissionAllowed = true;
    }
}

 @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    switch (requestCode) {
        case REQUEST_PERMISSIONS: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                isPermissionAllowed = true;

            } else {
                Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();

            }
        }
    }
}

LocationService.java位置服务.java

  public class LocationService extends Service implements LocationListener{

boolean isGPSEnable = false;
boolean isNetworkEnable = false;
double latitude,longitude;
LocationManager locationManager;
Location location;
private Handler mHandler = new Handler();
private Timer mTimer = null;
long notify_interval = 1000;
public static String str_receiver = "servicetutorial.service.receiver";
Intent intent;




public LocationService() {

}

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

@Override
public void onCreate() {
    super.onCreate();

    mTimer = new Timer();
    mTimer.schedule(new TimerTaskToGetLocation(),5,notify_interval);
    intent = new Intent(str_receiver);
}

@Override
public void onLocationChanged(Location location) {
 **//you can get updated location here**
}

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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}

private void fn_getlocation(){
    locationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
    isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if (!isGPSEnable && !isNetworkEnable){

    }else {

        if (isNetworkEnable){
            location = null;
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000,0,this);
            if (locationManager!=null){
                location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if (location!=null){

                    Log.e("latitude",location.getLatitude()+"");
                    Log.e("longitude",location.getLongitude()+"");

                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                    fn_update(location);
                }
            }

        }


        if (isGPSEnable){
            location = null;
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
            if (locationManager!=null){
                location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (location!=null){
                    Log.e("latitude",location.getLatitude()+"");
                    Log.e("longitude",location.getLongitude()+"");
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                    fn_update(location);
                }
            }
        }


    }

}

private class TimerTaskToGetLocation extends TimerTask{
    @Override
    public void run() {

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                fn_getlocation();
            }
        });

    }
}

private void fn_update(Location location){

    intent.putExtra("latutide",location.getLatitude()+"");
    intent.putExtra("longitude",location.getLongitude()+"");
    sendBroadcast(intent);
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android - 在不打开应用程序的情况下在后台访问位置 - Android - Access location in background without opening app 使用 OkHttp3 WebSocket 和 Retrofit 连续跟踪 android 设备位置 - Using OkHttp3 WebSocket with Retrofit to continuously track an android devices location 如何在Android测验应用程序中跟踪分数 - How to track score in an Android quiz app 如何使用appium在Android应用程序Google地图中设置位置 - How to set Location in android app Google maps using appium 如何在Android的后台服务中获取当前位置 - How to get current location in background service in android 由多个合作伙伴预先加载后,我们如何使用Android应用程序跟踪设备数量? - How can we track number of devices using our Android app after being preloaded by multiple partners? 当应用程序被破坏或进入后台时,Android 位置服务停止工作 - Android location service stop working when app destroyed or goes in background 如何在Android中使用加速计跟踪路径? - How to track path using accelerometer in android? 使用模拟位置的Android错误测试应用 - Android Error testing app using Mock Location 如何跟踪 android 应用程序中的变量? - How can I keep track of a variable in android app?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM