Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/226.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Android应用程序中未接收Firebase云推送通知_Android_Firebase_Push Notification_Firebase Cloud Messaging - Fatal编程技术网

在Android应用程序中未接收Firebase云推送通知

在Android应用程序中未接收Firebase云推送通知,android,firebase,push-notification,firebase-cloud-messaging,Android,Firebase,Push Notification,Firebase Cloud Messaging,我没有收到我的应用程序的推送通知。我已经包括了清单文件、MainActivity文件、MyFireBaseMessagingService文件、build.gradle文件和googl-services.json。我真的被这个问题难倒了。我去Firebase composer写消息,但没有收到任何消息。我可以硬编码字符串文件中的值,并收到一个通知,但我想要更动态的东西。这就是为什么我试图找出如何从FCM发送推送通知,但我似乎遗漏了一些内容或输入了一些错误的内容 维护性文件 package com

我没有收到我的应用程序的推送通知。我已经包括了清单文件、MainActivity文件、MyFireBaseMessagingService文件、build.gradle文件和googl-services.json。我真的被这个问题难倒了。我去Firebase composer写消息,但没有收到任何消息。我可以硬编码字符串文件中的值,并收到一个通知,但我想要更动态的东西。这就是为什么我试图找出如何从FCM发送推送通知,但我似乎遗漏了一些内容或输入了一些错误的内容

维护性文件

package com.example.testaaedapp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;

import java.net.URI;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageButton logoButton;
    private ImageView blueButton, greenButton, orangeButton, yellowButton, redButton, darkBlueButton;
    public Button callButton;
    private final String CHANNEL_ID = "Alerts";
    private final int notificationId = 001;
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        logoButton = findViewById(R.id.imageButton);
        logoButton.setOnClickListener(this);

        blueButton = findViewById(R.id.bluepuzzlepiece);
        blueButton.setOnClickListener(this);

        redButton = findViewById(R.id.redpuzzlepiece);
        redButton.setOnClickListener(this);

        greenButton = findViewById(R.id.greenpuzzlepiece);
        greenButton.setOnClickListener(this);

        orangeButton = findViewById(R.id.orangepuzzlepiece);
        orangeButton.setOnClickListener(this);

        yellowButton = findViewById(R.id.yellowpuzzlepiece);
        yellowButton.setOnClickListener(this);

        darkBlueButton = findViewById(R.id.darkbluepuzzlepiece);
        darkBlueButton.setOnClickListener(this);

        callButton = findViewById(R.id.button);
        callButton.setOnClickListener(this);

        displayNotification();
        // Get token
        // [START retrieve_current_token]
        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                    @Override
                    public void onComplete(@NonNull Task<InstanceIdResult> task) {
                        if (!task.isSuccessful()) {
                            Log.w(TAG, "getInstanceId failed", task.getException());
                            return;
                        }

                        // Get new Instance ID token
                        String token = task.getResult().getToken();

                        // Log and toast
                        String msg = getString(R.string.msg_token_fmt, token);
                        Log.d(TAG, msg);
                        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                });
        // [END retrieve_current_token]

    }
        int requestCode = 0;
    public void onClick(View view) {

        if (view.getId() == R.id.button && ActivityCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            Log.d("STATE", "Call Button DOES NOT WORK");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, requestCode);
            return;
        } else if (view.getId() == R.id.button && ActivityCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
//            else if (view.getId() == R.id.button && ActivityCompat.checkSelfPermission(MainActivity.this,
//                    Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
            Log.d("STATE", "Call Button DOES WORK");
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:480-240-9255"));
            startActivity(callIntent);


        } else {
            switch (view.getId()) {
                case R.id.imageButton:
                    setContentView(R.layout.activity_main);
                    break;

                case R.id.bluepuzzlepiece:

                    break;

                case R.id.redpuzzlepiece:
                    Intent blogIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.aaed.org/blog"));
                    startActivity(blogIntent);
                    break;

                case R.id.greenpuzzlepiece:
                    Intent videoIntent = new Intent(Intent.ACTION_VIEW);
                    videoIntent.setData(Uri.parse("https://www.youtube.com/channel/UCUwPShLvnCOTeQILvAtneOw"));
                    startActivity(videoIntent);
                    break;

                case R.id.yellowpuzzlepiece:
                    Intent secondActivity = new Intent(this, SecondActivity.class);
                    startActivity(secondActivity);
                    break;

                case R.id.orangepuzzlepiece:
                    Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.aaed.org"));
                    startActivity(webIntent);
                    break;

                case R.id.darkbluepuzzlepiece:
                    Intent schoolIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.aaed.org/online-course-content"));
                    startActivity(schoolIntent);


            }

        }

    }

    public void displayNotification () {
        createNotificationChannel();
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_puzzlepieces)
                .setContentTitle("Test Message")
                .setContentText("This is text")
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText(getString((R.string.another_string))));

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

        // notificationId is a unique int for each notification that you must define
        notificationManager.notify(notificationId, builder.build());
    }

    public void createNotificationChannel() {
        // 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 = getString(R.string.channel_name);
            String description = getString(R.string.channel_description);
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            /

/ Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == requestCode)
        {
            if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                Intent callIntent = new Intent(Intent.ACTION_CALL);
                callIntent.setData(Uri.parse("tel:480-240-9255"));
                startActivity(callIntent);
            }
        }
清单文件

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

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality.
    -->
    <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/AppTheme">

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps"></activity>
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="AAED" />
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_puzzlepieces" />
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorAccent" />

        <activity
            android:name=".MainActivity"
            android:label="Autism Academy"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".SecondActivity"
            android:label="Locations"></activity>

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />
        <!-- [START firebase_service] -->
        <service
            android:name=".MyFirebaseMessagingService"
            android:exported="false"
            android:enabled="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>


        <!-- [END firebase_service] -->
    </application>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>

</manifest>

我也遇到过类似的问题。我已经尝试了一切——在我看来,主要原因是所有的服务迟早都会被系统扼杀。唯一的方法是确保将通知发送到系统托盘,而不是应用程序。为此,您需要使用数据消息通知

FCM通知有两种类型:通知消息和数据消息

数据消息被传送到系统托盘并始终显示-即使服务未运行

通知消息如下所示:

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification":{
      "title":"Portugal vs. Denmark",
      "body":"great match!"
    }
  }
}
并触发FirebaseMessagingService的MessageCeaved()方法。许多设备(尤其是华为和小米)都试图尽一切努力终止后台服务,以防止电池耗尽。因此FirebaseMessagingService不是处理通知的最佳方式

第二种类型是数据消息:

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "data":{
      "Nick" : "Mario",
      "body" : "great match!",
      "Room" : "PortugalVSDenmark"
    }
  }
}
此类型由系统托盘处理,因此您不需要运行任何服务来获取通知。这是一种更方便的方法,但据我所知,它无法通过控制台实现

您可能需要服务器API来发送数据消息。


阅读了解更多详细信息。

我也遇到过类似的问题。我已经尝试了一切——在我看来,主要原因是所有的服务迟早都会被系统扼杀。唯一的方法是确保将通知发送到系统托盘,而不是应用程序。为此,您需要使用数据消息通知

FCM通知有两种类型:通知消息和数据消息

数据消息被传送到系统托盘并始终显示-即使服务未运行

通知消息如下所示:

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification":{
      "title":"Portugal vs. Denmark",
      "body":"great match!"
    }
  }
}
并触发FirebaseMessagingService的MessageCeaved()方法。许多设备(尤其是华为和小米)都试图尽一切努力终止后台服务,以防止电池耗尽。因此FirebaseMessagingService不是处理通知的最佳方式

第二种类型是数据消息:

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "data":{
      "Nick" : "Mario",
      "body" : "great match!",
      "Room" : "PortugalVSDenmark"
    }
  }
}
此类型由系统托盘处理,因此您不需要运行任何服务来获取通知。这是一种更方便的方法,但据我所知,它无法通过控制台实现

您可能需要服务器API来发送数据消息。

阅读更多细节