android – 如何在睡眠模式下运行服务?

android – 如何在睡眠模式下运行服务?,第1张

概述我有实现位置监听器的服务.现在我的问题是如何确保我的服务即使在睡眠模式下也能捕获位置.我读过有关报警管理器的内容 alarm.setRepeating(AlarmManager.RTC_WAKEUP, triggerAtMillis, intervalMillis, operation); 但如何使用它.这是我的代码..任何帮助将不胜感激.. 我的服务 public class LocationC 我有实现位置监听器的服务.现在我的问题是如何确保我的服务即使在睡眠模式下也能捕获位置.我读过有关报警管理器的内容

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;@OverrIDepublic voID onCreate() {    inteval=10*1000;    startLocationListener(inteval);}@OverrIDepublic 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,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) {}

}

解决方法 如果您想确保 *** 作系统不会杀死/回收您的服务,您需要将其作为前台服务.默认情况下,所有服务都是后台服务,这意味着当OS需要资源时它们将被终止.有关详细信息,请参阅此 doc

基本上,您需要为您的服务创建一个通知,并指出它是前台.这样,用户将看到持久通知,因此他知道您的应用正在运行,并且 *** 作系统不会终止您的服务.

以下是如何创建通知(在您的服务中执行此 *** 作)并使其成为前台的简单示例:

Intent intent = new Intent(this,typeof(SomeActivityInYourApp));PendingIntent pi = PendingIntent.getActivity(this,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 vIEwstartForeground(SERVICE_NOTIFICATION_ID,notification);

请注意,上述示例是基本的,不包含取消通知的代码等.此外,当您的应用程序不再需要该服务时,它应该调用stopForeground以删除通知并允许您的服务被杀死,不这样做是浪费资源.

总结

以上是内存溢出为你收集整理的android – 如何在睡眠模式下运行服务?全部内容,希望文章能够帮你解决android – 如何在睡眠模式下运行服务?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1127430.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-30
下一篇 2022-05-30

发表评论

登录后才能评论

评论列表(0条)

保存