I am having a Simple AutoStart Application with TimerTask implementation, that works fine in almost many devices. The problem is that it is not working in Samsung Galaxy Y(2.3.6) and DELL XCD35(2.2). When the device boots TimerTask works for some seconds and then shuts down. I check in the Application->Manage Application, I saw that the Applcation was already in Force Stop State. That means some how my Application gets stopped after some seconds. So, what is the reason for this weird behaviour in these two devices, if anyone has the solution do share it.
Below is my code.
MyReceiver.java
public class MyReceiver extends BroadcastReceiver{
private Timer mTimer = new Timer();
@Override
public void onReceive(Context context, Intent arg1) {
Toast.makeText(context, "Device Booted", Toast.LENGTH_LONG).show();
Log.d("TAG","Device Booted");
mTimer.scheduleAtFixedRate(new MyTimerTask(), 2000,2000);
}
private class MyTimerTask extends TimerTask
{
@Override
public void run() {
Log.d("TAG","TimerTask executed....");
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.autostart.app"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
</manifest>
I think in some of the
AndroidOSsometimes the OS kills the threads that are running while theDevicesBootswhich Android is not familiar with or doesn’t recognize it. This is the reason why theTimerTaskis working in some Devices and in some Devices just works for a 5-10 seconds and then the Application isForceStoppedautomaticallyby the Android OS onDeviceBoot(Note – Its Force Stop from Manage Application and not Force close so I am not getting any error in the Logcat).So in that case the solution is to use the
inbuiltMechanismwhichAndroidOSrecognizes and doesn’t kill it and keeps it in a running mode. In this case I managed usingAlarmManagerto perform my task and it works.I might not be right but my final solution was to use
AlarmManagerto make my Application working in every Device.UPDATE:
AlaramManager is critical system service that runs all the time.