我正在开发一个在后台运行并侦听来自服务器的通知的服务。此服务必须在设备启动时启动。不知何故,我无法让它发挥作用。服务启动,但随后它被系统停止。
即使遵循https://stackoverflow.com/a/7690600/981393中提出的架构,在服务启动后,我发现系统正在强制停止。
所以我想知道,这是应该的方式吗?
任何帮助将不胜感激。
接收机
public class SSBankBootReceiver extends BroadcastReceiver {
private static final String TAG = "SSBankBootReceiver";
private static final long PERIOD = 60000 * 1;
@Override
public void onReceive(Context ctxt, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Log.d(TAG, "Boot completed.");
startTestService(ctxt);
}
}
private void startTestService(Context ctxt) {
Log.d(TAG, "Starting test service...");
Intent i = new Intent(ctxt, TestService.class);
ctxt.startService(i);
}
服务
public class TestService extends Service {
private static final String TAG = "TestService";
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
printMessages();
super.onStartCommand(intent, flags, startId);
return START_REDELIVER_INTENT;
}
private void printMessages() {
// TODO Auto-generated method stub
while ( true) {
try {
Log.d(TAG, "Imprimiendo nuevo mensaje...");
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
清单
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".DashboardActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="<package>.service.SSBankBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<service android:name="<package>.service.TestService"></service>
</application>
日志
11-04 19:38:04.916: I/ActivityManager(276): Force stopping service ServiceRecord{41135258 u0 <package>/.service.TestService}
答案 0 :(得分:0)
这就是我解决这个问题的方法:
//do things you want
super.onStartCommand(intent, flags, startId);
return START_REDELIVER_INTENT; //this is the ANSWER