简体   繁体   English

如何在屏幕睡眠时让Android应用在后台运行?

[英]How to make an android app run in background when the screen sleeps?

I am developing a Tracking app, which keeps tracks of the user by getting his current location for every 3 secs. 我正在开发一个跟踪应用程序,它通过每3秒获取当前位置来保持用户的跟踪。 I am able to fetch the lat long values when the screen is on. 我可以在屏幕打开时获取lat long值。 but when the screen sleeps. 但是当屏幕睡觉时 i am unable to fetch the datas. 我无法获取数据。

CODE: 码:

@Override
public void onLocationChanged(Location location) {
    mLastLocation = location;
    if (mCurrLocationMarker != null)
    {
        mCurrLocationMarker.remove();
    }
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    latLngcurrent = new LatLng(location.getLatitude(), location.getLongitude());

    Toast.makeText(context,String.valueOf(latitude)+" "+String.valueOf(longitude), Toast.LENGTH_LONG).show();

    Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));


    Log.d("onLocationChanged", "Exit");
    Toast.makeText(this, "exiting LocationChanged ", Toast.LENGTH_SHORT).show();
    }

The above given onLocationChanged method fetches the lat lon values for every 3 seconds. 上面给出的onLocationChanged方法每3秒获取一次lat lon值。 What should i do to make this method run even if the screen sleeps. 即使屏幕休眠,我该怎么做才能使这个方法运行。 I have read about Wakelock dont know how to implement it, any help will be appreciated. 我读过关于Wakelock不知道如何实现它,任何帮助将不胜感激。 Thanks in advance. 提前致谢。

Note: The app runs perfectly when multi tasking is done, 注意:完成多任务后应用程序运行完美,

使用作业调度程序每隔3秒获取一次位置它也适用于屏幕睡眠时https://developer.android.com/reference/android/app/job/JobScheduler.html

You need to make use of Service to get location updates even if screen sleep or your app is not open. 即使屏幕睡眠或您的应用未打开,您也需要使用Service来获取位置更新。

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

public class MyLocationService extends Service
{
    private static final String TAG = "MyLocationService";
    private LocationManager mLocationManager = null;
    private static final int LOCATION_INTERVAL = 3000;
    private static final float LOCATION_DISTANCE = 10f;

    LocationListener[] mLocationListeners = new LocationListener[] {
            new LocationListener(LocationManager.GPS_PROVIDER),
            new LocationListener(LocationManager.NETWORK_PROVIDER)
    };

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        Log.e(TAG, "onStartCommand");
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    public void onCreate()
    {
        Log.e(TAG, "onCreate");
        initializeLocationManager();
        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[1]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "network provider does not exist, " + ex.getMessage());
        }
        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[0]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "gps provider does not exist " + ex.getMessage());
        }
    }

    @Override
    public void onDestroy()
    {
        Log.e(TAG, "onDestroy");
        super.onDestroy();
        if (mLocationManager != null) {
            for (int i = 0; i < mLocationListeners.length; i++) {
                try {
                    mLocationManager.removeUpdates(mLocationListeners[i]);
                } catch (Exception ex) {
                    Log.i(TAG, "fail to remove location listners, ignore", ex);
                }
            }
        }
    }

    private void initializeLocationManager() {
        Log.e(TAG, "initializeLocationManager");
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }
    }

    // create LocationListener class to get location updates
    private class LocationListener implements android.location.LocationListener
    {
        Location mLastLocation;

        public LocationListener(String provider)
        {
            Log.e(TAG, "LocationListener " + provider);
            mLastLocation = new Location(provider);
        }

        @Override
        public void onLocationChanged(Location location)
        {
            Log.e(TAG, "onLocationChanged: " + location);
            mLastLocation.set(location);
        }

        @Override
        public void onProviderDisabled(String provider)
        {
            Log.e(TAG, "onProviderDisabled: " + provider);
        }

        @Override
        public void onProviderEnabled(String provider)
        {
            Log.e(TAG, "onProviderEnabled: " + provider);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras)
        {
            Log.e(TAG, "onStatusChanged: " + provider);
        }
    }
}

Add MyLocationService into your AndroidManifest.xml also: MyLocationService添加到AndroidManifest.xml

<service android:name=".MyLocationService" android:process=":mylocation_service" />

Don't forgot to add below two permissions in your AndroidManifest.xml file: 不要忘记在AndroidManifest.xml文件中添加以下两个权限:

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

Start Service from an activity: 从活动开始服务:

You can start a service from an activity or other application component by passing an Intent (specifying the service to start) to startService() . 可以启动一个service通过传递一个Intent(指定服务开始),以从一个活动或其它应用程序组件startService() The Android system calls the service's onStartCommand() method and passes it the Intent. Android系统调用服务的onStartCommand()方法并将其传递给Intent。

Intent intent = new Intent(this, MyLocationService.class);
startService(intent);

Update: 更新:

You need to hold partial wake lock to run service even after device screen off. 即使在设备屏幕关闭后,您仍需要保持部分唤醒锁定以运行服务。

If you hold a partial wake lock, the CPU will continue to run, regardless of any display timeouts or the state of the screen and even after the user presses the power button. 如果保持部分唤醒锁定,CPU将继续运行,无论显示超时或屏幕状态如何,甚至在用户按下电源按钮之后。

To acquire wake lock: 要获得唤醒锁定:

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

To release it: 要发布它:

wakeLock.release();

Try using Service or JobScheduler and implement LocationListener 尝试使用ServiceJobScheduler并实现LocationListener

@Override
public void onLocationChanged(Location location) {
   mLastLocation = location;
   if (mCurrLocationMarker != null)
   {
      mCurrLocationMarker.remove();
   }
   latitude = location.getLatitude();
   longitude = location.getLongitude();
   latLngcurrent = new LatLng(location.getLatitude(),location.getLongitude());

   Toast.makeText(context,String.valueOf(latitude)+" "+String.valueOf(longitude), Toast.LENGTH_LONG).show();

   Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));

   Log.d("onLocationChanged", "Exit");
   Toast.makeText(this, "exiting LocationChanged ", Toast.LENGTH_SHORT).show();
}

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

相关问题 屏幕休眠时如何使用Media Player在Android中播放音频文件 - How to play the audio file in android using mediaplayer when screen sleeps 如何让安卓应用始终在后台运行? - How to make an android app to always run in background? Android如何保持kivy服务后台运行(切换其他App或锁屏时服务仍然运行)? - How to keep kivy service running in background in Android (service still run when switch to other App or lock the screen)? 将密码屏幕添加到可在设备休眠时重新锁定的应用程序吗? - Adding a PASSWORD screen to app that re-locks when device sleeps? 如何在手机开机且没有其他内容在后台运行时使android应用启动? - How to make android app start when phone is switched on and nothing else is allowed to run in background? 如何仅在屏幕打开/唤醒时使android后台服务启动 - how to make android background service start only when screen is on/wakeup 如何使我的android应用在后台运行? - How can I make my android app run on the background? 如何使整个离子Android应用程序作为后台服务运行? - How to make entire ionic android app to run as background service? 如何使android应用在后台运行,服务示例? - how to make android app to run in background, service example? 如何在Android应用程序进入后台时隐藏屏幕信息 - How to hide screen informations off Android app when it goes to the background
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM