实际上,您不需要指定操作,因为您AlarmReceiver.class
在意图中使用了该类。
在您的AndroidManifest.xml
中,确保您在<application>
标签中有接收者定义,例如:
<receiver android:name="AlarmReceiver">
编辑:好的,有两种方法可以使用您的广播接收器。
1)从您提供的代码中AlarmReceiver.java
,将包含:
public final class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
}
}
和HelloAndroid2.java
:
public class HelloAndroid2 extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (10 * 1000), pendingIntent);
Toast.makeText(this, "Alarm set", Toast.LENGTH_LONG).show();
}
}
像这样,您可以将广播接收器设置为使用AndroidManifest.xml
和 标签<receiver ...>
2)第二种方式。通过这种方式,您可以只使用 1 个文件HelloWorld2.java
:
在您的活动中,创建您的广播接收器并注册它。
public class HelloWorld2 extends Activity {
private SharedPreferences prefs;
private String mName;
BroadcastReceiver alarmReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm worked", Toast.LENGTH_LONG).show();
}
};
public static final String ACTION_NAME = "com.helloworld.MYACTION";
private IntentFilter myFilter = new IntentFilter(ACTION_NAME);
@Override
protected void onPause() {
unregisterReceiver(alarmReceiver);
super.onPause();
}
@Override
protected void onResume() {
registerReceiver(alarmReceiver, myFilter);
super.onResume();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(alarmReceiver, myFilter);
Intent intent = new Intent(ACTION_NAME);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (10 * 1000), pendingIntent);
Toast.makeText(this, "Alarm set", Toast.LENGTH_LONG).show();
}