我有正在实现位置侦听器的服务。现在我的问题是如何确保我的服务即使在睡眠模式下也能捕获位置。我读过有关警报管理器的内容
alarm.setRepeating(AlarmManager.RTC_WAKEUP, triggerAtMillis, intervalMillis, operation);
但如何使用它。这是我的代码..任何帮助将不胜感激..
我的服务
public class LocationCaptureService extends Service implements LocationListener {
public static int inteval;
java.sql.Timestamp createdTime;
LocationManager LocationMngr;
@Override
public void onCreate() {
inteval=10*1000;
startLocationListener(inteval);
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
private void startLocationListener(int inteval,String nwProvider) {
this.LocationMngr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
this.LocationMngr.requestLocationUpdates(LocationManager.GPS_PROVIDER, inteval, 0, this);
}
public void onLocationChanged(Location location) {
String status="c",S=null;
double longitude,lattitude,altitude;
g_currentBestLocation = location;
createdTime = new Timestamp (new java.util.Date().getTime());
longitude=location.getLongitude();
lattitude=location.getLatitude();
altitude=location.getAltitude();
//use this
}
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
如果您想确保您的服务不会被操作系统终止/回收,您需要将其设为前台服务。默认情况下,所有服务都是后台的,这意味着当操作系统需要资源时它们将被终止。详细请参考这个doc
基本上,您需要创建一个Notification
为您的服务并表明它是前台。这样,用户将看到持久通知,以便他知道您的应用程序正在运行,并且操作系统不会终止您的服务。
以下是如何创建通知(在您的服务中执行此操作)并将其置于前台的简单示例:
Intent intent = new Intent(this, typeof(SomeActivityInYourApp));
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(Resource.Drawable.my_icon);
builder.setTicker("App info string");
builder.setContentIntent(pi);
builder.setOngoing(true);
builder.setOnlyAlertOnce(true);
Notification notification = builder.build();
// optionally set a custom view
startForeground(SERVICE_NOTIFICATION_ID, notification);
请注意,上面的示例是基本的,不包含取消通知等的代码。此外,当您的应用程序不再需要该服务时,它应该调用stopForeground
为了删除通知并允许您的服务被终止,不这样做就是浪费资源。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)