Search code examples
androidnotificationsforeground-service

Why doesn't the notification appear?


I have made an app to test to show a foreground service and then tried to implement it in real app to close wifi after certain time, the code is the same as my test app but it doesn't show notification. the service works fine but without notification


Main Activity


package com.example.countdownclosewifi.UI;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;

import com.example.countdownclosewifi.MyService;
import com.example.countdownclosewifi.R;
import com.example.countdownclosewifi.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;
    private BroadcastReceiver receiver;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        // Intent filter to set the same action of the broadcast sender
        IntentFilter intentFilter_getRemainingTime = new IntentFilter();
        intentFilter_getRemainingTime.addAction("Count");

        // what will happen when the app receive a broadcast
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                int i = intent.getIntExtra("Show", 0);
                binding.timeLeft.setText(String.valueOf(i));
            }
        };
        registerReceiver(receiver, intentFilter_getRemainingTime);


        binding.start.setOnClickListener(view -> {
            if (binding.setTime.getText().toString().isEmpty() || Long.parseLong(binding.setTime.getText().toString()) == 0) {
                Toast.makeText(MainActivity.this, "Enter the duration", Toast.LENGTH_SHORT).show();
            } else {
                Intent serviceIntent = new Intent(this, MyService.class);
                int time = Integer.parseInt(binding.setTime.getText().toString());
                serviceIntent.putExtra("Time", time);
                if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){
                    startForegroundService(serviceIntent);

                }
                else {
                    startService(serviceIntent);
                }

            }

        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}

Service class


package com.example.countdownclosewifi;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
//import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.IBinder;

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

import com.example.countdownclosewifi.UI.MainActivity;

import java.util.Timer;
import java.util.TimerTask;

public class MyService extends Service {
    private WifiManager wifiManager;
    private int timeRemaining;
    private Timer timer;
    //    Intent intent;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        IntentFilter intentFilter_stop = new IntentFilter();
        intentFilter_stop.addAction("Stop timer");


        timeRemaining = intent.getIntExtra("Time", 0);
        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {

                if (timeRemaining == 0) {
                    wifiManager.setWifiEnabled(false);
                    timer.cancel();
                    stopSelf();
                }

                setNotification(timeRemaining);

                Intent intent = new Intent();
                intent.setAction("Count");
                intent.putExtra("Show", timeRemaining);
                sendBroadcast(intent);

                timeRemaining -= 1;


            }
        }, 0, 1000);

        return START_STICKY;
    }

    public void setNotification(int timeRemaining) {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent =
                PendingIntent.getActivity(this, 0, notificationIntent, 0);

        String channel_id = "id";
        Notification notification;
        if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O) {
            notification = new Notification.Builder(this, channel_id)
                    .setContentTitle("You are running out of time")
                    .setContentText(String.valueOf(timeRemaining))
                    .setSmallIcon(R.drawable.wifi_24)
                    .setContentIntent(pendingIntent)
                    .setOnlyAlertOnce(true)
                    .build();
        } else {
            notification = new NotificationCompat.Builder(this, channel_id)
                    .setContentTitle("You are running out of time")
                    .setContentText(String.valueOf(timeRemaining))
                    .setSmallIcon(R.drawable.wifi_24)
                    .setContentIntent(pendingIntent)
                    .setOnlyAlertOnce(true)
                    .build();
        }

        // Notification ID cannot be 0.
        startForeground(1, notification);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String id = "Notification Channel";
            CharSequence name = "notification";
            NotificationChannel notificationChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_DEFAULT);
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(notificationChannel);
        }



    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);
    }
}


Manifest


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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.CountDownCloseWIFI">
        <activity android:name=".UI.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyService"/>
    </application>

</manifest>

it's so clear but i cant see what i am missing to show this notification.


Solution

  • I Solved it, the problem was that the Notification ID was not the same as the Channel ID