Lal*_*ani 7 android android-widget android-manifest android-layout
我有一个简单的AutoStart应用程序TimerTask实现,几乎在许多设备中工作正常.问题是它没有工作Samsung Galaxy Y(2.3.6)和DELL XCD35(2.2).当设备启动TimerTask工作几秒钟然后关闭.我查了一下Application->Manage Application,我看到Applcation已经在Force Stop州.这意味着我的应用程序在几秒钟后停止运行.那么,weird behaviour这两个设备的原因是什么,如果有人有解决方案分享它.
以下是我的代码.
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....");
}
}
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
我认为有时Android OS操作系统会杀死正在运行的线程,而Devices BootsAndroid 不熟悉或无法识别它。这就是为什么它TimerTask在某些设备中工作,而在某些设备中仅工作 5-10 秒,然后应用程序ForceStopped automatically由 Android 操作系统打开Device Boot(注意 - 它从管理应用程序强制停止而不是强制关闭,所以我不在 Logcat 中出现任何错误)。
因此,在这种情况下,解决方案是使用能够inbuilt Mechanism识别Android OS但不会杀死它并使其保持运行模式的 。在这种情况下,我设法使用它AlarmManager来执行我的任务并且它有效。
我可能不正确,但我的最终解决方案是让AlarmManager我的应用程序在每个设备上运行。
@Override
public void onReceive(Context context, Intent arg1) {
Intent myIntent = new Intent(context, AlarmService.class);
PendingIntent pendingIntent = PendingIntent.
getService(context, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + 2000, 2000, pendingIntent);
}
Run Code Online (Sandbox Code Playgroud)
更新:
AlaramManager is critical system service that runs all the time.
| 归档时间: |
|
| 查看次数: |
1974 次 |
| 最近记录: |