我有正在实现位置侦听器的服务。现在我的问题是如何确保我的服务即使在睡眠模式下也能捕获位置。我已经阅读了有关警报管理器的信息
alarm.setRepeating(AlarmManager.RTC_WAKEUP, triggerAtMillis, intervalMillis, operation);
Run Code Online (Sandbox Code Playgroud)
但是如何使用它。这是我的代码..任何帮助将不胜感激..
我的服务
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) {}
Run Code Online (Sandbox Code Playgroud)
}
如果要确保操作系统不会杀死/回收您的服务,则需要使其成为前台服务。默认情况下,所有服务都是后台的,这意味着它们将在操作系统需要资源时被杀死。有关详细信息,请参阅此文档
基本上,您需要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);
Run Code Online (Sandbox Code Playgroud)
请注意,以上示例是基本示例,除其他外,不包含用于取消通知的代码。另外,当您的应用不再需要该服务时,应调用该服务stopForeground以删除通知并终止您的服务,否则这样做会浪费资源。
| 归档时间: |
|
| 查看次数: |
10667 次 |
| 最近记录: |