我正在尝试使用BroadcastReceiver和AlarmManager来设置一次性警报。我不知道为什么它不起作用。我究竟做错了什么?我没有例外,没有日志,没有来自IDE的建议,一切似乎都很好,但我的BroadcastReceiver中的onReceive方法永远不会被调用。
public void setAlarm(Context mContext) {
AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(mContext, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 505151550 ,intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 20);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
Log.d("alarm",cal.getTime().toString());
}
我从活动中调用它:
new MyManager().setAlarm(this);
但我也尝试过:new MyManager().setAlarm(MyActivity.this);
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("alarm","got into alarm receiver");
}}
AndroidManifest.xml中的:
<receiver android:name="com.example.AlarmReceiver"></receiver>
但我也试过
<receiver android:name=".AlarmReceiver"></receiver>
答案 0 :(得分:1)
尝试这样:它会在30秒后发出警报。
public class TestAlarmManager extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setAlarm(getApplicationContext());
}
public void setAlarm(Context mContext) {
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (30 * 1000), pendingIntent);
Toast.makeText(this, "Alarm set in " + 30 + " seconds",Toast.LENGTH_LONG).show();
}
}
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent arg1) {
Log.e("alarm","got into alarm receiver");
Toast.makeText(context, "Alarm Started..", Toast.LENGTH_LONG).show();
}
}
的AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.think.androidteststackoverflow"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher_3"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.think.androidteststackoverflow.TestAlarmManager"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlarmReceiver"></receiver>
</application>
</manifest>