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

6tqwzwtp  于 2022-12-25  发布在  Android
关注(0)|答案(1)|浏览(210)

我正在创建一个简单的通知应用程序,但它不显示任何通知。我已经使用BroadcastReceiver和服务来显示它。它不显示任何错误,但仍然不工作。

    • 主要活动. 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

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

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

<?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>

原木

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)

有什么问题吗?有没有操作系统验证。谢谢。

x8diyxa7

x8diyxa71#

此错误可能是因为您正在使用空通知。从onHandleIntent获取逻辑,并在调用context.startForeground(...)时使用它来构造通知
还有,AlarmManager::setRepeating在现代版本的Android中并不可靠,我建议你改用setAlarmClocksetExactAndAllowWhileIdle
我在我的GitHub here上有一个完整的闹钟应用程序示例,可能对您有用。

相关问题