我有一个带有 TimerTask
实现的简单 AutoStart
应用程序,几乎在许多设备上都能正常工作。问题是它在 Samsung Galaxy Y(2.3.6)
和 DELL XCD35(2.2)
中不工作。当设备启动时,TimerTask
工作几秒钟然后关闭。我检查了 Application->Manage Application
,我看到 Applcation 已经处于 Force Stop
状态。这意味着我的应用程序在几秒钟后如何停止。那么,这两种设备中出现这种奇怪行为
的原因是什么,如果有人有解决方案,请分享。
下面是我的代码。
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>
最佳答案
我会建议您使用 AlarmManager 而不是 TimerTask,因为我在许多设备中遇到了您描述的相同问题。
public void onReceive(Context context, Intent arg1) {
Toast.makeText(context, "Device Booted", Toast.LENGTH_LONG).show();
Log.d("TAG","Device Booted");
AlarmManager AM =(AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent();
intent.setAction("ALARM_MANAGER_ACTION");//can add any string action here
PendingIntent pi = PendingIntent.getBroadcast(mContext
.getApplicationContext(), 0, intent,0);
AM.set(AlarmManager.RTC,selectedTime, pi);
AM.setRepeating(AM.RTC_WAKEUP, System.currentTimeMillis()+2000, 2000, pi);
}
public class MyReceiver1 extends BroadcastReceiver{
//event will come here
private Timer mTimer = new Timer();
@Override
public void onReceive(Context context, Intent arg1) {
// check if event is same as you broadcasted through alarmManager
Toast.makeText(context, "Device Booted", Toast.LENGTH_LONG).show();
Log.d("TAG","TimerTask executed....");
}
在您的应用中添加一个广播接收器,它应该监听 ("ALARM_MANAGER_ACTION")
操作。并将此操作添加到 list 文件中。
我打赌它也适用于这两种设备。
关于android - AutoStart 应用程序无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8624270/