我正在开发的应用是一个聊天客户端,需要保持持续连接,它还是基于插件的,因此我的应用程序是这样开发的:客户端-HostService-多个子“服务”。
主服务是黏性的,持有唤醒锁并调用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清单文件(相关部分):
<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" />
startForeground()
的书籍示例。虽然“设置”应用程序显示我的服务正在运行,但SystemPanel Lite根本没有显示它,在多次刷新后仍是如此。 - CommonsWare