在服务的Android位置更新(Android location updates in a Serv

2019-07-20 12:14发布

我想要做这样的事情:

  • 当我的应用程序开始我要开始应该检查我的位置服务

  • 当应用程序被切换到后台我要停止服务

我有两个主要问题:

  1. 我怎样才能检测到我的应用程序切换到后台? 我哈弗一些活动,我想在我的MainActivity覆盖的onPause,但是当我开始的其他活动的onPause也被称为。

  2. 这个问题更重要的是:我的服务,检查我的位置应该看怎么样? 我试了几种方法,但没有成功。

我的服务是这样的,它不工作。 我应该怎么改变,使其工作?

package com.pivoscore.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;

public class LocationService extends Service {

    private LocationListener locationListener;

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

    @Override
    public int onStartCommand(final Intent intent, final int flags, final int startId) {
        super.onStartCommand(intent, flags, startId);
        return Service.START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        final LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        this.locationListener = new MyLocationListener();
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100, 0, this.locationListener);
    }

    private static class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(final Location location) {
        }

        @Override
        public void onProviderDisabled(final String provider) {
        }

        @Override
        public void onProviderEnabled(final String provider) {
        }

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

    }

}

Answer 1:

这将有助于exaclty你的需求量的信息,但不要忘记加入我的评论已经添加权限,也不要忘了在清单文件一小段代码片段添加服务标签继

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;

Intent intent;
int counter = 0;

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

@Override
public void onStart(Intent intent, int startId) {      
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    listener = new MyLocationListener();        
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
}

@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.v("STOP_SERVICE", "DONE");
    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);          
            /*final Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());         
            String Text = "";
            try {
                List<Address> addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);                
                Text = "My current location is: "+addresses.get(0).getAddressLine(0); 

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Text = "My current location is: " +"Latitude = " + loc.getLatitude() + ", Longitude = " + loc.getLongitude();  
            }
            */
            //Toast.makeText( getApplicationContext(), "Location polled to server", Toast.LENGTH_SHORT).show();
        }                               
    }

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


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


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

    }

}


Answer 2:

  1. 应用程序不在Android的可视组件。 它分为活动,他们每个人的运行时可见,停下来,否则破坏。 因此,不存在整个应用程序将背景的概念,活动被暂停和恢复他们的个人知名度的基础上,是完全独立在这个问题上的其他活动。

  2. 您的服务应符合其定位管理注册onCreate()在其相同的,注销onDestroy() 在其onBind()应当返回一个Messenger对象。 而且,在onLocationChanged()应当通过其共享发送消息Messenger 。 无需使用START_STICKY因为你不希望服务运行所有的时间做。

  3. 该活动(可在App的任何活动)只需要调用bindService()在其onStart()该服务将启动,如果没有准备好,并且活动会得到一个Messenger的服务。 此外,活动应该调用unbindService()从它onStop() 没事的时候被绑定到它的服务将自动停止。

  4. 如果您需要做的第3点的东西在应用程序(任务)的水平,实现了Application类,并使用它onCreate()onTerminate() 应用类没有暂停或停止就像一个活动。



Answer 3:

我建议你使用谷歌提供的最新位置API(也到2.2版本兼容)。

这里有一个例子说明如何使用: https://github.com/chenjishi/android_location_demo

当你的应用程序运行的背景下,您可以拨打断开停下来的位置更新。



Answer 4:

试试这个代码。通过使用这个,你可以找到你的应用是否在前台或后台。 希望这会帮助你。

try {
    foreground = new ForegroundCheckTask().execute(ctx).get();
}

======================================


class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {

@Override
protected Boolean doInBackground(Context... params) {
    final Context context = params[0].getApplicationContext();
    return isAppOnForeground(context);
}

private boolean isAppOnForeground(Context context) {
    ActivityManager activityManager = (ActivityManager) context
            .getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> appProcesses = activityManager
            .getRunningAppProcesses();
    if (appProcesses == null) {
        return false;
    }
    final String packageName = context.getPackageName();


    String activePackageName = activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
    if (activePackageName.equals(packageName)) {
        return true;
    }
    else{
        return false;
    }


}

}


文章来源: Android location updates in a Service