我在单击按钮时创建了alarmmanager。但手机重启后无法正常工作。我的AlarmbroadcastReceiver无法在电话重启时调用。它在手机锁定时起作用,应用程序终止,但在手机重启后无法正常工作,我创建了一个进度条,该按钮会在单击按钮时启动,并在警报广播触发后停止,但在手机重启时不会停止。我添加了我的按钮单击事件和广播接收器类
按钮单击事件
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pb1.setVisibility(View.VISIBLE);
progress_edit.putBoolean("progress_one", true);
progress_edit.apply();
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intnt = new Intent(getApplicationContext(), AlarmbroadcastReceiver.class);
intnt.setAction("com.ex.Alarm");
PendingIntent pending = PendingIntent.getBroadcast(getApplicationContext(), 0, intnt, 0);
manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 120000, pending);
Log.d("Broadcast ","Fired");
}
});
BroadcastReceiver类
@Override
public void onReceive(Context context, Intent intent) {
Log.d("inside","broadcast receive");
if(intent.getAction().equalsIgnoreCase("com.ex.Alarm"))
{
enterSys_progress_edit.putBoolean("progress_one", false);
enterSys_progress_edit.apply();
Toast.makeText(context,"Receive",Toast.LENGTH_LONG).show();
}
}
我的 list 文件
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.krutarth.alarm">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlarmbroadcastReceiver" android:enabled="true" android:exported="false" android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
</manifest>
最佳答案
重新启动手机后,所有警报都会重置,因此在重新启动时创建一个回调,如下所示
public class BootCompletedIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
////// reset your alrarms here
}
}
}
还应将此添加到您的 list 中以注册广播
<receiver android:name=".receiver.BootCompletedIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
创建一个方法说,
setMyalarm(){
// here set the alarm as u need
}
现在调用此方法setMyAlarm,无论何时何地需要设置该特定警报,无论是单击按钮还是重新启动接收器
关于android - 电话重启后,Alarmmanager无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41197416/