Search code examples
androidandroid-studiobroadcastreceiver

Notification is not showing in broadcast receiver


Notification is not coming even when the app is open or closed. But toast comes only when the app is open.I have a main activity and another class which extends broadcastlistener. In activity I am requesting permissions and in class I have written code for notification to come on incoming calls. Please help me with some code snippets. Below is my activity class.

public class PhoneActivity extends AppCompatActivity {
  private static final int REQUEST_READ_PHONE_STATE = 1;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_phone);

    int readContactsPermissionLog = ContextCompat.checkSelfPermission(this,Manifest.permission.READ_CALL_LOG);
    if(readContactsPermissionLog != PackageManager.PERMISSION_GRANTED) {
      ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CALL_LOG}, REQUEST_READ_PHONE_STATE);
    }
    int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
      ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE);
    }
  }
}

This is my class which extends broadcastreceiver.

public class PhoneState extends BroadcastReceiver {
  public static final String NOTIFICATION_CHANNEL_ID = "10001" ;
  private final static String default_notification_channel_id = "default" ;
  boolean connected  = true;
  @RequiresApi(api = Build.VERSION_CODES.O)
  @Override
  public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals("android.intent.action.PHONE_STATE")) {
      String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
      if (state != null) {
        if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
          if (!intent.getExtras().containsKey(TelephonyManager.EXTRA_INCOMING_NUMBER)) {
            Log.i("Call receiver", "skipping intent=" + intent + ", extras=" + intent.getExtras() + " - no number was supplied");
            return;
          }
          String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
          System.out.println("incoming number is " + number);
          if (number != null) {
            if (number.equals("some number i have given for testing")) {
              System.out.println("number matched");
                           createNotificationChannel(number,context);
          createNotificationChannel(number,context);

              // Toast.makeText(context, "number is " + number, Toast.LENGTH_SHORT).show();
            } else {
          createNotificationChannel(number,context);
            //  Toast.makeText(context, "number is " + number, Toast.LENGTH_LONG).show();
              System.out.println("not matched");
            }
          } else {
            System.out.println("number is null");
          }
        }
      }
    }
  }




 private void createNotificationChannel(String number,Context context) {
        String CHANNEL_ID = "10";
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
          CharSequence name = "Phone";
          int importance = NotificationManager.IMPORTANCE_HIGH;
          NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
          channel.setDescription(number);
          // Register the channel with the system; you can't change the importance
          // or other notification behaviors after this
          NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
          notificationManager.createNotificationChannel(channel);
        }
      }

I have added this in my manifest file.

 <receiver android:name=".PhoneState"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" />
            </intent-filter>
        </receiver>

And this is my layout activity.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Activity.PhoneActivity">
</LinearLayout>

Solution

  • Be sure that you have android version less than 8, otherwise you should use Notification Channel to create notification https://developer.android.com/training/notify-user/channels