I'm developing a Service that runs in the background and listens to notifications from a server. This Service has to start when the device boots. Somehow, I can not get it to work. The Service starts, but then it's stopped by the system.
Even following the schema proposed in https://stackoverflow.com/a/7690600/981393, after the Service is started I see that it's being force stopped by the system.
So I'm wondering, is this the way is supposed to be?
Any help would be appreciated.
Receiver
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);
}
Service
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();
}
}
}
}
Manifest
<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>
Log
11-04 19:38:04.916: I/ActivityManager(276): Force stopping service ServiceRecord{41135258 u0 <package>/.service.TestService}