[英]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 尝试使用Service或JobScheduler并实现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.