Уведомление не отображается в приемнике вещания - PullRequest
0 голосов
/ 25 февраля 2020

Уведомление не приходит, даже когда приложение открыто или закрыто. Но тост приходит только тогда, когда приложение открыто. У меня есть основной вид деятельности и другой класс, который расширяет широковещательный прослушиватель. В действии я запрашиваю разрешения, а в классе я написал код для уведомления о входящих вызовах. Пожалуйста, помогите мне с некоторыми фрагментами кода. Ниже приведен мой класс занятий.

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);
    }
  }
}

Это мой класс, который расширяет вещательный приемник.

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>

И это мой макет деятельности.

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

Ответы [ 2 ]

2 голосов
/ 26 февраля 2020

Возможно, вы не добавляете Сервисы в свой Манифест. В случае активности, автоматически добавляемой 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>

Надеюсь, это вам поможет.

1 голос
/ 25 февраля 2020

Убедитесь, что у вас android версия меньше 8, в противном случае вам следует использовать канал уведомлений для создания уведомления https://developer.android.com/training/notify-user/channels

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...