我需要每隔30秒启动闹钟,我需要在不运行应用程序的情况下激活它。但无论应用程序是否运行,AlarmReceiver都不会被调用。有什么建议? start方法在MainActivity.java类
中 public void start() {
Calendar calendar=Calendar.getInstance();
calendar.add(Calendar.SECOND, 30);
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pintent);
Log.d("alarm","alarm set for alarm receiver");
}
我的接收器文件
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Toast.makeText(context,"Alarm Receiver ",Toast.LENGTH_SHORT).show();
Log.d("Alarm","Alarm receive");
}
}
清单文件:
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity" android:configChanges="keyboardHidden|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".GetLocationService"/>
<receiver android:name=".AlarmReceiver" android:enabled="true"/>
</application>
这里我可以设置闹钟,但我没有收到闹钟
答案 0 :(得分:0)
在此页面中,您需要完成一个示例:
https://www.thepolyglotdeveloper.com/2014/10/use-broadcast-receiver-background-services-android/
显然你必须改变这条线:
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
要
PendingIntent pintent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
将您的开始方法更改为:
public void start() {
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
int interval = 30 * 1000; // 30 seconds of interval.
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
}
如果有效,请告诉我。
答案 1 :(得分:0)
我最近遇到了这个问题。问题出在我的自定义 Parcelable 对象上,使用原语可以正常工作。这个答案对我有帮助:Sending Extras to onReceive only retrieves ALARM_COUNT