简体   繁体   English

Android 通知未按预期工作

[英]Android notification not working as expected

I want to create notification WITH SOUND & VIBRATION that will appear every 3 days.我想创建每 3 天出现一次的带有声音和振动的通知。 I cannot make it happen我不能让它发生

Tried almost every solution I found on the internet.几乎尝试了我在互联网上找到的所有解决方案。 You will see it from my code.你会从我的代码中看到它。 With my code, the sound is not working, vibration is not working, notification is showing more times in a row even when cancelled, it is not showing on the screen when locked even though I set priority to high.使用我的代码,声音不起作用,振动不起作用,即使取消通知也会连续显示更多次,即使我将优先级设置为高,它也不会在锁定时显示在屏幕上。 super weird超级奇怪

this is function that sets notification in MainActivity:这是在 MainActivity 中设置通知的函数:

public void setNotification() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());

        calendar.set(Calendar.HOUR_OF_DAY, 10);
        calendar.set(Calendar.MINUTE, 45);

        Intent myIntent = new Intent(this, NotifyService.class);
        int ALARM1_ID = 10000;
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this, ALARM1_ID, myIntent, 0);
        AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        assert alarmManager != null;
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 3, pendingIntent);
    }

this is BroadcastReceiver that triggers the notification:这是触发通知的 BroadcastReceiver:

public class NotifyService extends BroadcastReceiver {

    @SuppressLint("ResourceAsColor")
    @Override
    public void onReceive(Context context, Intent intent) {

            NotificationManager notificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel("my_channel_01ee",
                        "Channel human readable titlee",
                        NotificationManager.IMPORTANCE_HIGH);
                channel.enableVibration(true);
                channel.setVibrationPattern(new long[]{
                        0
                });

                channel.enableLights(true);
                channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);

                channel.setLightColor(Color.GRAY);
                channel.enableLights(true);
                channel.setDescription("descrioptiom");
                    AudioAttributes audioAttributes = new AudioAttributes.Builder()
                            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                            .build();
                channel.setSound(alarmSound, audioAttributes);
                notificationManager.createNotificationChannel(channel);

            }

            Intent notificationIntent = new Intent(context, FoodInspectorActivity.class);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                    notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.Builder notification = new NotificationCompat.Builder(context, "my_channel_01ee");

            int color = 0xfffffff;
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                notification.setSmallIcon(R.drawable.magnifier_final);
                notification.setColor(color);
            } else {
                notification.setSmallIcon(R.drawable.magnifier_final);
            }

            notification.setContentTitle("FoodScan")
                    .setContentText("Scan some new products? Just click!")
                    .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.launcher_icon))
                    .setSound(alarmSound)
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)
                    .setDefaults(Notification.DEFAULT_LIGHTS )
                    .setVibrate(new long[]{0, 500, 1000});

            assert notificationManager != null;
            notificationManager.notify(5, notification.build());

        }
}

With this code, the sound is not working, vibration is not working, notification is showing more times in a row even when cancelled, it is not showing on the screen when locked even though I set priority to high.使用此代码,声音不起作用,振动不起作用,即使取消通知也会连续显示更多次,即使我将优先级设置为高,它也不会在锁定时显示在屏幕上。 super weird超级奇怪

Step 1: Create Method in your MainActivity and use AlarmManager to set alarm at specified time, and call the method in OnCreate第一步:在你的MainActivity创建Method并使用AlarmManager设置指定时间的闹钟,并在OnCreate调用该方法

public void my(){

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,21);
calendar.set(Calendar.MINUTE,47);
if (calendar.getTime().compareTo(new Date()) < 0) 
calendar.add(Calendar.DAY_OF_MONTH, 1);
Intent intent = new Intent(getApplicationContext(),NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
if (alarmManager != null) {
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,pendingIntent);
}


 }

I'm setting my alarm every day at 09:47 PM我每天晚上09:47设置闹钟

Step 2: Create BroadcastReceiver to listen when the alarm happens第 2 步:创建 BroadcastReceiver 以在警报发生时进行侦听

public class NotificationReceiver extends BroadcastReceiver {

   @Override
   public void onReceive(Context context, Intent intent) {

   NotificationHelper notificationHelper = new NotificationHelper(context);
   notificationHelper.createNotification();

   }
}

I'm creating this class named NotificationReceiver and extends BroadcastReceiver , in onReceive there is Class named NotificationHelper , don't confuse i will explain this Class for next steps.我正在创建这个名为NotificationReceiver类并扩展BroadcastReceiver ,在onReceive有一个名为NotificationHelper类,不要混淆,我将在下一步中解释这个类。

Step 3: Create the Notification class第 3 步:创建 Notification 类

class NotificationHelper {

 private Context mContext;
 private static final String NOTIFICATION_CHANNEL_ID = "10001";

 NotificationHelper(Context context) {
 mContext = context;
 }

void createNotification()
{

Intent intent = new Intent(mContext , NotificationActivity.class);

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext,
        0 /* Request code */, intent,
        PendingIntent.FLAG_UPDATE_CURRENT);


NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle("Title")
        .setContentText("Content")
        .setAutoCancel(false)
        .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
        .setContentIntent(resultPendingIntent);

NotificationManager mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
{
    int importance = NotificationManager.IMPORTANCE_HIGH;
    NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
    notificationChannel.enableLights(true);
    notificationChannel.setLightColor(Color.RED);
    notificationChannel.enableVibration(true);
    notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
    assert mNotificationManager != null;
    mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
    mNotificationManager.createNotificationChannel(notificationChannel);
}
assert mNotificationManager != null;
mNotificationManager.notify(0 /* Request Code */, mBuilder.build());

   }
}

This class handles the notification这个类处理通知

Step 4: Come back to Step 2: and call the Notification Class第 4 步:回到第 2 步:并调用通知类

NotificationHelper notificationHelper = new NotificationHelper(context);
notificationHelper.createNotification();

Finally go to your AndroidManifest.xml and register this最后去你的AndroidManifest.xml并注册这个

<receiver android:name=".NotificationReceiver"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM