我长期陷入困境......
我想使用闹钟管理器在特定时间显示通知,现在它可以在下面列出的情况下工作:
这是代码AlarmReceiver.java,已经将所有必需的权限添加到AndroidManifest.xml中:
@Override
public void onReceive(Context context, Intent intent) {
WakeLocker.acquire(context);
String action = intent.getAction();
Log.d(TAG, action); //when app is killed and device is locked, no info is shown at the logcat
if (ACTION_ALARM.equals(action)) {
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2 * 1000);
notify(context, "Jello!");
}
WakeLocker.release();
}
public static void alarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
intent.setAction(ACTION_ALARM);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 5 * 1000, pi);
} else {
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 5 * 1000, pi);
}
}
private void notify(Context context, String msg) {
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, InfoActivity.class), 0);
Notification notification =
new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(context.getString(R.string.alarm))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setAutoCancel(true)
.setContentIntent(contentIntent).build();
notificationManager.notify(1, notification);
}
已添加权限:
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.VIBRATE"/>
答案 0 :(得分:1)
我刚刚找到解决方案,将名为FLAG_INCLUDE_STOPPED_PACKAGES的标志设置为警报的意图,事情会顺利进行。 以下是Android Developers
中的插图答案 1 :(得分:0)
有一天我遇到了类似的问题并在网上找到了一个解决方案,当收到广播接收器时,它正在敲响电话。
因此,尝试创建此类,并在调用broadcastreceiver时调用MyWakeLock.acquire()
。完成执行任何警报后,您还应该致电MyWakeLock.release()
。
package your.package.name;
import android.content.Context;
import android.os.PowerManager;
public abstract class MyWakeLock {
private static PowerManager.WakeLock wakeLock;
public static void acquire(Context c) {
if (wakeLock != null) wakeLock.release();
PowerManager pm = (PowerManager) c.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE, MainActivity.APP_TAG);
wakeLock.acquire();
}
public static void release() {
if (wakeLock != null){
wakeLock.release();
}
wakeLock = null;
}
}
答案 2 :(得分:0)