本教程来自 android-er, 主要活动(AndroidScheduledActivity.java)重复启动AlarmManager以触发BroadcastReceiver(MyScheduledReceiver.java).在MyScheduledReceiver的onReceive()方法中,它间接启动另一个活动(MyScheduledActi
主要活动(AndroidScheduledActivity.java)重复启动AlarmManager以触发BroadcastReceiver(MyScheduledReceiver.java).在MyScheduledReceiver的onReceive()方法中,它间接启动另一个活动(MyScheduledActivity.java).这样活动(MyScheduledActivity.java)将在预定的时间间隔内启动.
现在我会使用AutoStart自动启动,但我无法编写AutoStartNotifyReceiver.
请你能告诉我如何管理它吗?
非常感谢 !
主要活动,AndroidScheduledActivity.java:
public class AndroidScheduledActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button buttonStart = (Button)findViewById(R.id.start); buttonStart.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View arg0) { 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(); }}); } }
然后是BroadcastReceiver,MyScheduledReceiver.java
public class MyScheduledReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { Intent scheduledIntent = new Intent(context, MyScheduledActivity.class); scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(scheduledIntent); } }
和我的问题AutoStartNotifyReceiver:
public class AutoStartNotifyReceiver extends BroadcastReceiver { private final String BOOT_COMPLETED_ACTION = "android.intent.action.BOOT_COMPLETED"; @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals(BOOT_COMPLETED_ACTION)){ ???????????????????? } } }您的AutoStartNotifyReceiver扩展了BroadcastReceiver类,因为当设备重置时警报会被清除.所以,在这个类的onReceive中(你有问号的地方)你需要用相同的代码重新设置警报(当然没有你在第一次使用时完成它的完成()) AndroidScheduledActivity的onClick方法.
然后,您需要在Manifest中放入以下条目,让系统知道在系统启动时启动AutoStartNotifyReceiver:
<receiver android:name=".AutoStartNotifyReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver>
除了Manifest中的许可:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
现在,假设您只有一个警报,并且每次只设置一个警报.如果不是这样的话,那会更复杂一些.但根据您提供的小信息,我的解决方案应该做您想要的.
此外,由于您是新手,这只是一个善意的提醒:当有人提供问题的充分答案时,提出问题的人(您)通过单击答案旁边的复选框接受答案.这是回答的人得到信任.欢迎来到SO!