Android 屏幕锁定时服务仍在运行
我有一个连接屏幕,其中有一个搜索按钮,单击后会发布一个可发现设备的列表,我单击所需的设备进行配对和连接,连接建立,当我锁定屏幕时连接丢失,我如何改进代码以使服务仍然工作?这就是我试图实现它的方式,onCreate()、onStart()和onResume()也在launchApplication()中实现Android 屏幕锁定时服务仍在运行,android,bluetooth,screen-lock,Android,Bluetooth,Screen Lock,我有一个连接屏幕,其中有一个搜索按钮,单击后会发布一个可发现设备的列表,我单击所需的设备进行配对和连接,连接建立,当我锁定屏幕时连接丢失,我如何改进代码以使服务仍然工作?这就是我试图实现它的方式,onCreate()、onStart()和onResume()也在launchApplication()中实现 我假设launchActivity是从活动的生命周期方法中调用的 如果是这样-您基本上是在创建“附加”到活动的后台逻辑,即UI组件。 这是个坏主意 为什么? 因为当资源不足时,Android在
我假设launchActivity是从活动的生命周期方法中调用的 如果是这样-您基本上是在创建“附加”到活动的后台逻辑,即UI组件。 这是个坏主意 为什么? 因为当资源不足时,Android在回收后台活动及其衍生的线程方面相当快 您应该做的是明确地通知Android,该逻辑将被视为后台逻辑,即。 未连接到活动的可见性,无法打开屏幕 要做到这一点,你应该申报 在舱单中:
<service
android:name="MyConnectionService"
android:icon="@drawable/icon"
android:label="@string/service_name" >
</service>
这其实很正常。只要你离开应用程序,android生命周期调用
onDestroy()
方法,所有连接都应该离线。因此,您需要一个在后台进一步工作的过程。在这里,您可以使用安卓服务组件。只要您正在使用这些资源,它就会工作,只要它完成服务
将要关闭的过程。所以这取决于你需要什么。如果您需要在后台永远工作的后台服务,您应该使用service
的startForeground()
方法
有关服务的更多信息,请点击此处:能否发布用onPause()编写的代码?。因为当你锁定屏幕时,会调用onPause生命周期方法。我解决了这个问题,它与我调用onPause()的方法有关,谢谢!
<service
android:name="MyConnectionService"
android:icon="@drawable/icon"
android:label="@string/service_name" >
</service>
public class MyConnectionService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// <------------ place connection logic here
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
public class MyConnectionService extends IntentService {
@Override
protected void onHandleIntent(Intent intent) {
// <--------- run connection logic on a dedicated thread here
}
}
Notification notification = new Notification(R.drawable.icon, getText(R.string.msg_text),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MyConnectionService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(SERVICE_NOTIFICATION_ID, notification);