我需要在特定时间打开活动并执行特定任务,即使应用程序被杀死也是如此。即使从多任务窗口窗格中删除应用程序也是如此。
截至目前,我正在使用闹钟管理器来完成此任务,如下所示。
Intent myIntent = new Intent(getBaseContext(),MyScheduledReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(),
0, myIntent, 0);
AlarmManager alarmManager
= (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
long interval = 60 * 1000; //
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), interval, pendingIntent);
finish();
onReceive方法如下:
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent scheduledIntent = new Intent(context, MyScheduledActivity.class);
scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scheduledIntent);
}
问题是,它会在应用程序处于后台时打开活动。不是在关闭或不在后台堆栈中时(多任务窗格)。
请把我搞笑。我挣扎了。
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.exercise.AndroidScheduledActivity"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AndroidScheduledActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MyScheduledActivity" />
<receiver android:process=":remote"
android:name="MyScheduledReceiver" />
</application>
</manifest>