我将建立一个带闹钟功能的应用程序,以提醒患者按时服药。
但目前的问题是警报管理器未在小米手机上触发,而且它在Android 6.0中的三星音符4上运行。在将代码实现到我的项目之前,我创建了一个新项目并使用相同的代码来测试它。在新项目中,只要自动启动权限授予,代码就能完美运行。警报将按时触发,甚至重启手机,启动接收器也可以重新启动警报,但它只对我的应用程序无效。
以下是我的代码。
OnAlarmReceiver.java
public class OnAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("MyApp", "Received wake up from alarm manager.");
long rowid = intent.getExtras().getLong(RemindersDbAdapter.KEY_ROWID);
WakeReminderIntentService.acquireStaticLock(context);
Intent i = new Intent(context, ReminderService.class);
i.putExtra(RemindersDbAdapter.KEY_ROWID, rowid);
context.startService(i);
}
}
ReminderManager.java
public class ReminderManager {
private Context mContext;
private AlarmManager mAlarmManager;
public ReminderManager(Context context) {
mContext = context;
mAlarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
}
public void setReminder(Long taskId, Calendar when) {
Intent i = new Intent(mContext, OnAlarmReceiver.class);
i.putExtra(RemindersDbAdapter.KEY_ROWID, (long)taskId);
int broadcastID = Integer.parseInt(taskId+""+when.getTime().getDate()+""+when.getTime().getYear()+""+taskId);
broadcastID = (int)when.getTimeInMillis();
System.out.println("Alarm when : "+ when.getTimeInMillis());
PendingIntent pi = PendingIntent.getBroadcast(mContext, broadcastID, i, PendingIntent.FLAG_ONE_SHOT);
System.out.println("Alarm Set ID : "+broadcastID);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
AlarmManager.AlarmClockInfo ac= new AlarmManager.AlarmClockInfo(when.getTimeInMillis(), pi);
mAlarmManager.setAlarmClock(ac, pi);
System.out.println("Android 6.0 Marshmallow and above.");
}else if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, when.getTimeInMillis(), pi);
System.out.println("Android 4.4 Kikkat and above.");
}else{
mAlarmManager.set(AlarmManager.RTC_WAKEUP, when.getTimeInMillis(), pi);
System.out.println("Android 4.3 Jelly Bean and below.");
}
}
}
清单文件:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
忘了提,我已经在清单文件中注册了.OnAlarmReceiver
<receiver android:name=".OnBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver android:name=".OnAlarmReceiver" />
我的主要问题是它在我创建的新项目中使用相同的代码进行测试,但是在我的主项目中没有用。
有人能帮助我吗?提前谢谢。
答案 0 :(得分:0)
在清单
中注册OnAlarmReceiver
<receiver android:name=".OnAlarmReceiver" />
答案 1 :(得分:0)
<receiver android:name=".OnAlarmReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>