简体   繁体   English

与 AlarmManager 和服务一起使用时,通知在 Android 中不起作用

[英]Notification not working in Android when using with AlarmManager and Service

I was creating a simple notification app, but which is not showing any notification.我正在创建一个简单的通知应用程序,但没有显示任何通知。 I have used BroadcastReceiver and service for showing it up.我已经使用 BroadcastReceiver 和服务来显示它。 It doesn't showing any errors but still not working.它没有显示任何错误,但仍然无法正常工作。

MainActivity.java主活动.java

package com.example.myapplication;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends  AppCompatActivity
{
    int NOTIFICATION_REMINDER_NIGHT = 1;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setBroadcast(this);


    }

    void setBroadcast(Context context)
    {
        Intent notifyIntent = new Intent(this, MyReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast
                (context, NOTIFICATION_REMINDER_NIGHT, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,  System.currentTimeMillis(),
                1000 * 60 * 15, pendingIntent);
    }
}


MyNewIntentService.java我的新意图服务.java


package com.example.myapplication;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentSender;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;

public class MyNewIntentService extends IntentService
{
    private static final int NOTIFICATION_ID = 1;

    @Override
    public void onCreate() {
        super.onCreate();
        startForeground(NOTIFICATION_ID, new Notification());
    }

    /**
     * @param name
     * @deprecated
     */
    public MyNewIntentService(String name) {
        super(name);
    }

    public MyNewIntentService(){
        super("service");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent)
    {
        Notification.Builder builder = new Notification.Builder(this);
        builder.setContentTitle("My title");
        builder.setContentText("This is the body");
        builder.setSmallIcon(R.drawable.ic_launcher_background);

        Intent notifyIntent  = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,2, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        builder.setContentIntent(pendingIntent);

        Notification notificationCompat = builder.build();

        NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this);
        managerCompat.notify(NOTIFICATION_ID, notificationCompat);
    }
}



MyReceiver.java我的接收器.java

package com.example.myapplication;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

public class MyReceiver extends BroadcastReceiver
{

    @Override
    public void onReceive(Context context, Intent intent)
    {
        Intent intent1 = new Intent(context, MyNewIntentService.class);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(new Intent(context, MyNewIntentService.class));
        } else {
            context.startService(new Intent(context, MyNewIntentService.class));
        }

    }
}



AndroidManifest.xml AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication"
        tools:targetApi="31">
        <service
            android:name=".MyNewIntentService"
            android:enabled="true"
            android:exported="true"></service>

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>

        <receiver android:name=".MyReceiver"
            android:enabled="true"
            android:exported="false"/>

    </application>

</manifest>

log日志

android.app.RemoteServiceException: 
Bad notification for startForeground
                                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2275)
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                                        at android.os.Looper.loop(Looper.java:257)
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:8246)
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626)
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1016)

what's the problem?有什么问题? is there any os validations.是否有任何操作系统验证。 Thanks.谢谢。

This error is likely because you're just using an empty notification.此错误很可能是因为您只是在使用空通知。 Take your logic from onHandleIntent , and use it to construct the notification when calling context.startForeground(...)onHandleIntent中获取您的逻辑,并在调用context.startForeground(...)时使用它来构造通知

Also, AlarmManager::setRepeating is not reliable in modern versions of Android.此外, AlarmManager::setRepeating在现代版本的 Android 中并不可靠。 I would recommend you use setAlarmClock or setExactAndAllowWhileIdle instead.我建议您改用setAlarmClocksetExactAndAllowWhileIdle

I have a complete example of an alarm app on my GitHub here , which may be useful for you.我的 GitHub 上有一个完整警报应用程序示例,可能对您有用。

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

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