Mahi
Mahi

Reputation: 1732

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. It doesn't showing any errors but still not working.

MainActivity.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>

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.

Upvotes: 0

Views: 670

Answers (1)

PPartisan
PPartisan

Reputation: 8231

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(...)

Also, AlarmManager::setRepeating is not reliable in modern versions of Android. I would recommend you use setAlarmClock or setExactAndAllowWhileIdle instead.

I have a complete example of an alarm app on my GitHub here, which may be useful for you.

Upvotes: 1

Related Questions