【发布时间】:2011-09-13 03:30:57
【问题描述】:
我遇到了一个问题,即使我持有唤醒锁并且我已调用 startForeground,我的服务也会被终止。当平板电脑 (ASUS Transformer TF101) 发生这种情况时,停止服务而不调用 onDestroy。没有其他可见的应用程序,并且 log cat 没有显示任何异常(没有“内存不足”消息等)。被杀死后,服务立即重新启动。
我正在开发的应用程序是一个聊天客户端,需要持续连接,它也是基于插件的,所以我的应用程序是这样开发的:Client - HostService - Multiple child 'Services'。
主机服务是粘性的,持有唤醒锁并调用 startForeground(并显示这样的通知),子服务不粘性,不持有唤醒锁并且是后台服务。
如果客户端本身是打开的,则不会出现问题,但我想要的模型是用户可以使用设备并保持连接(接收消息等),而无需始终打开客户端本身。
任何人都可以解释为什么服务会以这种方式被杀死,如果是这样的话,可以防止它发生吗?正如聊天客户端在用户登录和注销时显示的那样,并且服务终止会杀死所有打开的连接,这会使聊天客户端“反弹”。目前,它似乎每 15 到 45 分钟发生一次。
另外,如果有人知道一种保持套接字连接持续打开而不在整个连接期间保持唤醒锁的方法,我很想听听!
主机服务源的修剪测试用例版本如下。
public class HostService extends Service
{
PowerManager m_powerManager = null;
PowerManager.WakeLock m_wakeLock = null;
@Override
public IBinder onBind( Intent intent )
{
return m_serviceImplementation;
}
@Override
public void onCreate()
{
super.onCreate();
}
@Override
public void onDestroy()
{
if( m_wakeLock != null )
{
m_wakeLock.release();
m_wakeLock = null;
}
stopForeground( true );
super.onDestroy();
}
@Override
public int onStartCommand( Intent intent, int flags, int startId )
{
// Display a notification about us starting. We put an icon in the
// status bar.
Notification notification = createNotification();
startForeground( R.string.service_running, notification );
if( m_powerManager == null )
{
m_powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
}
if( m_wakeLock == null )
{
m_wakeLock = m_powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Keep background services running");
m_wakeLock.acquire();
}
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
/**
* Create a notification to show the service is running
*/
private Notification createNotification()
{
CharSequence text = getText( R.string.service_running );
CharSequence title = getText( R.string.app_name );
// The PendingIntent to launch our activity if the user selects this
// notification
PendingIntent contentIntent = PendingIntent.getActivity( this, 0, new Intent(this, MainChat.class) , 0 );
Notification notification = new Notification( android.R.drawable.sym_action_chat, title, System.currentTimeMillis() );
notification.setLatestEventInfo( this, title, text, contentIntent );
return notification;
}
private final IMessageInterface.Stub m_serviceImplementation = new IMessageInterface.Stub()
{
...
};
}
Android Manifest(相关位):
<uses-sdk android:minSdkVersion="11" android:targetSdkVersion="11" />
<service android:name="com.mydomain.chatClient.server.HostService" android:exported="true" android:enabled="true" android:process=":remote"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
【问题讨论】:
标签: java android android-service