广播接收器中未显示通知

Notification is not showing in broadcast receiver

即使打开或关闭应用程序也不会收到通知。但是只有当应用程序 open.I 有一个主 activity 和另一个 class 扩展 broadcastlistener 时才会出现吐司。在 activity 中,我请求权限,在 class 中,我编写了用于通知来电的代码。请帮我一些代码片段。下面是我的 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);
    }
  }
}

这是我的 class,它扩展了 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);
        }
      }

我已将其添加到我的清单文件中。

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

这是我的布局 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>

请确保您的 android 版本低于 8,否则您应该使用 Notification Channel 创建通知 https://developer.android.com/training/notify-user/channels

可能是您没有在清单中添加服务。如果 activity 由 android studio 自动添加,但 android 不会在 Manifist 中自动添加服务。 所以你需要在你的清单中添加这段代码。

       <service
        android:name=".FireBaseMessagingService.GettingDeviceTokenService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
    <service
        android:name=".FireBaseMessagingService.MyFirebaseMessagingService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

希望对你有所帮助。