如何在android上始终保持GPS /位置服务? [英] How to keep GPS / location service on android always on?

查看:162
本文介绍了如何在android上始终保持GPS /位置服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何保持android上的GPS /位置服务始终在?



如果有代码可以在Playstore上实现这个或任何可用的应用程序?



我需要跟踪我的员工当他们在交付路线。

解决方案

我以前做过类似的事情。
这里是位置服务:

p $ p $ public class LocationService extends Service {
public static final String BROADCAST_ACTION = 你好,世界;
private static final int TWO_MINUTES = 1000 * 60 * 2;
public LocationManager locationManager;
public MyLocationListener侦听器;
public Location previousBestLocation = null;

public long refreshTime = 60 * 1000;

意向意图;
int counter = 0;

@Override
public void onCreate(){
super.onCreate();
intent = new Intent(BROADCAST_ACTION);

$ b @Override
public int onStartCommand(Intent intent,int flags,int startId){
locationManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
listener = new MyLocationListener();
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED&&&& ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
// TODO:考虑调用
// ActivityCompat#requestPermissions
//在这里请求丢失的权限,然后覆盖
// public void onRequestPermissionsResult(int requestCode,String [] permissions,
// int [] grantResults)
//处理用户授予权限的情况。有关更多详细信息,请参阅文档
//获取ActivityCompat#requestPermissions。
返回START_STICKY;
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,refreshTime,100,listener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,refreshTime,100,listener);

返回START_STICKY;
}
// @覆盖
// public void onStart(Intent intent,int startId){
//}
$ b $ @覆盖
public IBinder onBind(意图意图){
return null;


protected boolean isBetterLocation(Location location,Location currentBestLocation){
if(currentBestLocation == null){
//新位置总是优于no位置
返回true;
}

//检查新的定位是新的还是旧的
long timeDelta = location.getTime() - currentBestLocation.getTime();
布尔isSignificantlyNewer = timeDelta> 2分钟;
布尔isSignificantlyOlder = timeDelta< -2分钟;
boolean isNewer = timeDelta> 0;

//如果距离当前位置超过两分钟,则使用新位置
//因为用户可能已经移动了
(如果是(isSignificantlyNewer)){
返回true;
//如果新位置超过两分钟,则必须更糟
} else if(isSignificantlyOlder){
return false;
}

//检查新的定位是否或多或少准确
int accuracyDelta =(int)(location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta> 0;
boolean isMoreAccurate = accuracyDelta< 0;
boolean isSignificantlyLessAccurate = accuracyDelta> 200;

//检查旧位置和新位置是否来自同一提供者
布尔isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());

//使用时间性和准确性的组合来确定位置质量
if(isMoreAccurate){
return true;
} else if(isNew&&< isLessAccurate){
return true;
} else if(isNew&&< isSignificantlyLessAccurate&&& isFromSameProvider){
return true;
}
返回false;


$ b $ **检查两个提供者是否相同* /
private boolean isSameProvider(String provider1,String provider2){
if( provider1 == null){
return provider2 == null;
}
返回provider1.equals(provider2);


$ b @Override
public void onDestroy(){
// handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();
Log.i(STOP_SERVICE,完成);
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED&&&& ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
// TODO:考虑调用
// ActivityCompat#requestPermissions
//在这里请求丢失的权限,然后覆盖
// public void onRequestPermissionsResult(int requestCode,String [] permissions,
// int [] grantResults)
//处理用户授予权限的情况。有关更多详细信息,请参阅文档
//获取ActivityCompat#requestPermissions。
return;
}
locationManager.removeUpdates(listener);
}

public static Thread performOnBackgroundThread(final Runnable runnable){
final Thread t = new Thread(){
@Override
public void run ){
尝试{
runnable.run();
}终于{b
$ b}
}
};
t.start();
return t;
}

public class MyLocationListener实现LocationListener
{

public void onLocationChanged(final Location loc)
{
Log。我(**************************************,位置已更改);
if(isBetterLocation(loc,previousBestLocation)){
loc.getLatitude();
loc.getLongitude();
intent.putExtra(Latitude,loc.getLatitude());
intent.putExtra(Longitude,loc.getLongitude());
intent.putExtra(Provider,loc.getProvider());
sendBroadcast(intent);
LocationHelper.sendLocation(loc.getLatitude(),loc.getLongitude(),$ b $ new MyPreferenceManager(App.context).getAuthToken());
Log.i(b8,Location:+ loc.getLatitude()+:+ loc.getLongitude());


$ b $ public void onProviderDisabled(String provider)
{
MyToast.makeText(getApplicationContext(),Gps Disabled,Toast.LENGTH_SHORT )。显示();


$ b public void onProviderEnabled(String provider)
{
MyToast.makeText(getApplicationContext(),Gps Enabled,Toast.LENGTH_SHORT) 。显示();


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

}



$ / code>

您需要在清单中添加此权限

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

另一件您应该知道的事情是GC认为没有足够的内存时可以终止服务应用程序在后台或被用户关闭)
当然使用返回START_STICKY; 在 onStartCommand 方法中导致重启该服务,但它将取决于可用内存


How to keep GPS / location service on android always on?

If there is code to implement this or any available app on playstore ?

I need to track my employees when they are in delivery routes.

解决方案

I did something like that before. here is the location service :

public class LocationService extends Service {
    public static final String BROADCAST_ACTION = "Hello World";
    private static final int TWO_MINUTES = 1000 * 60 * 2;
    public LocationManager locationManager;
    public MyLocationListener listener;
    public Location previousBestLocation = null;

    public long refreshTime = 60*1000;

    Intent intent;
    int counter = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        intent = new Intent(BROADCAST_ACTION);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        listener = new MyLocationListener();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return START_STICKY;
        }
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, refreshTime, 100, listener);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, refreshTime, 100, listener);

        return START_STICKY;
    }
//    @Override
//    public void onStart(Intent intent, int startId) {
//        }

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

    protected boolean isBetterLocation(Location location, Location currentBestLocation) {
        if (currentBestLocation == null) {
            // A new location is always better than no location
            return true;
        }

        // Check whether the new location fix is newer or older
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
        boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
        boolean isNewer = timeDelta > 0;

        // If it's been more than two minutes since the current location, use the new location
        // because the user has likely moved
        if (isSignificantlyNewer) {
            return true;
            // If the new location is more than two minutes older, it must be worse
        } else if (isSignificantlyOlder) {
            return false;
        }

        // Check whether the new location fix is more or less accurate
        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
        boolean isLessAccurate = accuracyDelta > 0;
        boolean isMoreAccurate = accuracyDelta < 0;
        boolean isSignificantlyLessAccurate = accuracyDelta > 200;

        // Check if the old and new location are from the same provider
        boolean isFromSameProvider = isSameProvider(location.getProvider(),
                currentBestLocation.getProvider());

        // Determine location quality using a combination of timeliness and accuracy
        if (isMoreAccurate) {
            return true;
        } else if (isNewer && !isLessAccurate) {
            return true;
        } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
            return true;
        }
        return false;
    }


    /** Checks whether two providers are the same */
    private boolean isSameProvider(String provider1, String provider2) {
        if (provider1 == null) {
            return provider2 == null;
        }
        return provider1.equals(provider2);
    }


    @Override
    public void onDestroy() {
        // handler.removeCallbacks(sendUpdatesToUI);
        super.onDestroy();
        Log.i("STOP_SERVICE", "DONE");
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        locationManager.removeUpdates(listener);
    }

    public static Thread performOnBackgroundThread(final Runnable runnable) {
        final Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    runnable.run();
                } finally {

                }
            }
        };
        t.start();
        return t;
    }

    public class MyLocationListener implements LocationListener
    {

        public void onLocationChanged(final Location loc)
        {
            Log.i("**************************************", "Location changed");
            if(isBetterLocation(loc, previousBestLocation)) {
                loc.getLatitude();
                loc.getLongitude();
                intent.putExtra("Latitude", loc.getLatitude());
                intent.putExtra("Longitude", loc.getLongitude());
                intent.putExtra("Provider", loc.getProvider());
                sendBroadcast(intent);
                LocationHelper.sendLocation(loc.getLatitude(), loc.getLongitude(),
                 new MyPreferenceManager(App.context).getAuthToken());
                Log.i("b8", "Location : "+ loc.getLatitude() + ":"+ loc.getLongitude());
            }
        }

        public void onProviderDisabled(String provider)
        {
            MyToast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
        }


        public void onProviderEnabled(String provider)
        {
            MyToast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
        }


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

        }

    }
}

you need to add this permissions in the manifest

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

another thing you should know is that GC can kill the service whenever thinks there is no enough memory (while app is in background or closed by user ) of course using return START_STICKY; in onStartCommand method cause restart the service but it'll be depends on free memory

这篇关于如何在android上始终保持GPS /位置服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆