简体   繁体   English

Android-定位服务仅在连接到计算机后才在后台运行

[英]Android - location service not running in background, only when connected to the computer

I have created a service that has a LocationListener. 我创建了一个具有LocationListener的服务。 In the Fragment i have a BroadcastReceiver that successfully receives location from the Service. 在Fragment中,我有一个BroadcastReceiver,可以从服务成功接收位置。 Everything works fine when the phone is connected to my computer and I have pressed "run" (not debug mode). 当电话连接到我的计算机并且我按下“运行”(不是调试模式)时,一切正常。 I receive location continuously when the screen on my phone is turned off as I can see in the "Run" console in Android Studio. 正如我在Android Studio的“运行”控制台中看到的那样,当手机屏幕关闭时,我会连续收到位置信息。

However when i disconnect my phone from the computer and turn the screen off, I stoped receiving location updates. 但是,当我断开手机与计算机的连接并关闭屏幕时,我停止接收位置更新。 Or I got only one or two location updates before it stoped. 或者,在停止之前,我仅获得了一两个位置更新。 Then when turning the screen on again the Service starts sending location updates. 然后,当再次打开屏幕时,服务将开始发送位置更新。

I have tried using a WakeLock on the Fragment and the Service, but it dosent seem to have any effect. 我曾尝试在Fragment和Service上使用WakeLock,但似乎没有任何效果。

Can someone help me please!?... :,( 有人能帮助我吗!?... :,(

In my Service I set a ArrayList->String in putExtra() that contains a Latitude and a TimeStamp so that I can see if the locationlistener did update location when screen is locked. 在我的服务中,我在putExtra()中设置了一个ArrayList-> String,它包含一个纬度和一个时间戳,以便我可以查看锁屏时listener是否确实更新了位置。 And in the Fragment I display the results in the view so that I can manually debug. 然后在“片段”中,将结果显示在视图中,以便可以手动调试。

Here is my Service code: 这是我的服务代码:

public class GpsService extends Service {

private LocationListener listener;
private LocationManager locationManager;
private Intent mIntent;

private ArrayList<String> latTimeArrayList = new ArrayList<>();

private PowerManager.WakeLock wakeLock;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    mIntent = new Intent("location_update");

    PowerManager mgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
    wakeLock.acquire();

    return START_NOT_STICKY;
}

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

@Override
public void onCreate() {

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    listener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {

            mIntent.putExtra("Latitude", location.getLatitude());
            mIntent.putExtra("Longitude", location.getLongitude());

            if(latTimeArrayList.size() < 10){

                latTimeArrayList.add(location.getLatitude() + " -> " + new Date());

            }else if(latTimeArrayList.size() == 10){
                mIntent.putExtra("latTimeArray", latTimeArrayList);
            }
            sendBroadcast(mIntent);
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    };

    //noinspection MissingPermission
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100, 0, listener);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 0, listener);

}

@Override
public void onDestroy() {
    super.onDestroy();
    if(locationManager != null){
        //noinspection MissingPermission
        locationManager.removeUpdates(listener);
        wakeLock.release();
    }
}

} }

private BroadcastReceiver broadcastReceiver;
ArrayList<String> aString = new ArrayList<>();
private String mmtext = "";
TextView debugtext = (TextView) mView.findViewById(R.id.hasCompletedTrack);
int doagain = 0;
@Override
public void onResume() {
    super.onResume();

    if(broadcastReceiver == null){
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try{
                    if (doagain == 0){
                        aString = (ArrayList<String>)intent.getExtras().get("latTimeArray");
                        if(aString != null || aString.size() != 0){

                            for (int i =0; i< aString.size(); i++){
                                mmtext += aString.get(i) + "\n";
                            }
                            doagain = 1;
                            debugtext.setText(mmtext);
                        }
                    }


                }catch(NullPointerException e){}

I found the answer... 我找到了答案...

I had to turn off PoweSaving mode on my Samsung Galaxy S6 edge. 我必须在三星Galaxy S6 edge上关闭PoweSaving模式

Also, in my broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { 另外,在我的broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) {

that's in my Fragment, I did some position calculations for every location update that I got from my Service with a Intent getExtra() (this is not in the code I posted). 那是在我的Fragment中,对于使用Intent getExtra()从服务中获得的每个位置更新,我都进行了一些位置计算(这不在我发布的代码中)。 However onReceive() only gets triggered when the screen is on(not locked). 但是onReceive()仅在屏幕打开(未锁定)时触发。 Therefore my calculations in the fragment were never triggered, only when the screen was on it triggered the calculation methods. 因此,仅在屏幕上触发该计算方法时,才触发该片段中的计算。

My solution to this was to handle all the calculations directly in my service. 我对此的解决方案是直接在我的服务中处理所有计算。

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

相关问题 后台服务Android中的位置监听器 - Location Listener in Background Service Android android后台服务中的位置列表器 - Location listner in android background service 当应用程序被破坏或进入后台时,Android 位置服务停止工作 - Android location service stop working when app destroyed or goes in background Android如何在用户杀死应用程序后继续运行后台服务? - Android How to keep Running the background service when app is killed by user? 在Android上运行警报的后台服务? - running a background service for an alarm on android? 我的 Android 11 应用程序在用户将其置于后台时停止运行,除非手机已连接到电源 - My Android 11 app stops running when the user puts it into the background unless the phone is connected to power Android,将位置请求作为后台服务,并将其发送到网络 - Android, location request as a background service, and sending this to network 如何在Android的后台服务中获取当前位置 - How to get current location in background service in android 服务已在运行,但不应使用后台服务代码定位 - Service already running while it shouldnt in Location Using Background Service code 我的服务在待机状态下运行,但仅在连接USB的情况下。 为什么? - My Service is running in standby but only if USB is connected. Why?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM