我开发了一个 android应用程序.我使用firebase进行通知.我阅读了firebase文档然后分别制作了它们.我可以使用InstanceID令牌向一台设备发送推送通知.但我无法向所有设备发送推送通知.请帮我.

MyFirebaseMessagingService.java

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */
    // [START receive_message]
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // Todo(developer): Handle FCM messages here.
        // If the application is in the foreground handle both data and notification messages here.
        // Also if you intend on generating your own notifications as a result of a received FCM
        // message,here is where that should be initiated. See sendNotification method below.
        Log.d(TAG,"From: " + remoteMessage.getFrom());
        Log.d(TAG,"Notification Message Body: " + remoteMessage.getNotification().getBody());
    }
    // [END receive_message]

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */
    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this,MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0 /* Request code */,intent,PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= ringtoneManager.getDefaultUri(ringtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_stat_ic_notification)
                .setContentTitle("FCM Message")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        notificationmanager notificationmanager =
                (notificationmanager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationmanager.notify(0 /* ID of notification */,notificationBuilder.build());
    }
}

MyFirebaseInstanceIDService.java

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";

    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the prevIoUs token had been compromised. Note that this is called when the InstanceID token
     * is initially generated so this is where you would retrieve the token.
     */
    // [START refresh_token]
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG,"Refreshed token: " + refreshedToken);

        // Todo: Implement this method to send any registration to your app's servers.
        sendRegistrationToServer(refreshedToken);
    }
    // [END refresh_token]

    /**
     * Persist token to third-party servers.
     *
     * Modify this method to associate the user's FCM InstanceID token with any server-side account
     * maintained by your application.
     *
     * @param token The new token.
     */
    private void sendRegistrationToServer(String token) {
        // Add custom implementation,as needed.
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

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

        if (getIntent().getExtras() != null) {
            for (String key : getIntent().getExtras().keySet()) {
                String value = getIntent().getExtras().getString(key);
                Log.d(TAG,"Key: " + key + " Value: " + value);
            }
        }

        Button subscribeButton = (Button) findViewById(R.id.subscribeButton);
        subscribeButton.setonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // [START subscribe_topics]
                FirebaseMessaging.getInstance().subscribetoTopic("news");
                Log.d(TAG,"Subscribed to news topic");
                // [END subscribe_topics]
            }
        });

        Button logTokenButton = (Button) findViewById(R.id.logTokenButton);
        logTokenButton.setonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG,"InstanceID token: " + FirebaseInstanceId.getInstance().getToken());
            }
        });
    }

}

的Manifest.xml

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

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

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

        <service
            android:name=".MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

        <service
            android:name=".MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>

    </application>

</manifest>

解决方法

你应该在清单上包括:
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/> 

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

更新

不再需要预先准备,因为“FCM所需的所有权限现在都由库自动添加”

android – Firebase推送通知无法正常工作的更多相关文章

  1. html5 移动端视频video的android兼容(去除播放控件、全屏)

    这篇文章主要介绍了html5 移动端视频video的android兼容,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  2. 如何使用Firebase在iOS上验证用户的电子邮件地址?

    我坚持使用firebase进行电子邮件验证.我四处寻找指导但没有帮助.在用户验证他的电子邮件后,我的代码仍然打印出用户尚未验证.我还在尝试习惯firebase的语法.这是我的代码:这是我注册部分的代码:解决方法您在签名之前检查了用户电子邮件是否已经过验证.这对我有用.

  3. ios – 1天后firebase crashlytics报告中没有数据

    解决方法对于那些仍然有问题的人.检查您的podfile中是否还有pod’Firebase/Crash’.当我删除旧的Firebase崩溃报告时,我的问题已修复.

  4. ios – Swift Firebase安全无法正常工作

    正如@M_G建议的那样,我从父母和.read中取出了.write.所以我的规则现在是:我现在得到这个输出:解决方法Firebase文档错误(暂时).在Firebase控制台中,打开规则模拟器.目前没有“密码”选项,我认为这是一个错误.如果您没有使用多个身份验证或多个身份验证在您的项目中无关紧要,请不要在您的规则中使用提供程序.否则,您可以测试此规则以进行密码验证:

  5. ios – Firebase:我应该将GoogleService-Info.plist添加到.gitignore吗?

    我正在将Firebase用于我想要开源的iOS项目.我上传之前是否应该将GoogleService-Info.plist添加到.gitignore我在Github上共享项目?我知道它包含我的API密钥,客户端ID等,这可能不安全公开?

  6. ios – Firebase动态链接中的customURLScheme是什么?

    在documentation中它说要将以下行添加到我的AppDelegate.swift:根据我的理解,这应该是您在info.plist中添加的相同链接.但是,我很困惑为什么在quickstart-iosrepo他们决定将其等同于“dlscheme”.任何人都可以帮我理解这个方案究竟是什么?

  7. FIrebase iOS集成崩溃 – 由无效的GOOGLE_APP_ID引起

    我正在尝试使用Xcode构建集成Firebase来构建我的Cordova应用程序,但是我得到了这个模糊的错误,我无法理解什么是错的.我已将GoogleService-Info.plist文件放在项目目录中,但仍无法构建.这是堆栈跟踪可能是什么问题,我不知道还有什么需要展示,所以请问.解决方法出于某种原因,Xcode始终忽略位于项目根目录中的GoogleService-Info.plist,并且未将其复制到项目的Resources文件夹中.我在那里手动复制文件,然后编译应用程序并运行得很好.

  8. 使用Firebase iOS Swift将特定设备的通知推送到特定设备

    我非常感谢PushNotifications的帮助.我的应用聊天,用户可以直接向对方发送短信.但是如果没有PushNotifications,它就没有多大意义.它全部设置在Firebase上.如何将推送通知从特定设备发送到特定设备?

  9. ios – Firebase Swift – 如何创建子项并将其id添加到另一个ref属性?

    如here所述,我想将Book对象存储在单独的ref中,并将其id值存储在User的books属性中每当我在应用程序中添加一本书时book对象是在Booksref中创建的,但我想立即将其id添加到User的用户书籍数组中.可以用一些漂亮的方式完成,而不是查询书籍,检索它的ID并将其添加到数组中吗?如果不是,查询刚刚创建的对象id的正确方法是什么?也许我不应该使用AutoId模式并在应用程序中为自己创建每个对象的唯一ID?解决方法您可以通过以下方式获取childByAutoId创建的密钥:

  10. ios – 默认应用尚未配置

    我试图将我的应用程序升级到新版本的Firebase.我浏览了设置指南,并编辑了我的所有代码以匹配新的语法.但是,当我运行应用程序时,我会收到这两个错误.我在AppDelegate中有FIRApp.configure(),并将GoogleServices-Info.plist导入到我的项目中.plist也有所有正确的信息.任何人遇到这个或知道如何解决它?

随机推荐

  1. bluetooth-lowenergy – Altbeacon库无法在Android 5.0上运行

    昨天我在Nexus4上获得了Android5.0的更新,并且altbeacon库停止了检测信标.似乎在监视和测距时,didEnterRegion和didRangeBeaconsInRegion都没有被调用.即使RadiusNetworks的Locate应用程序现在表现不同,一旦检测到信标的值,它们就不再得到更新,并且通常看起来好像信标超出了范围.我注意到的一点是,现在在logcat中出现以下行“B

  2. android – react-native动态更改响应者

    我正在使用react-native进行Android开发.我有一个视图,如果用户长按,我想显示一个可以拖动的动画视图.我可以使用PanResponder实现这一点,它工作正常.但我想要做的是当用户长按时,用户应该能够继续相同的触摸/按下并拖动新显示的Animated.View.如果您熟悉Google云端硬盘应用,则它具有类似的功能.当用户长按列表中的任何项目时,它会显示可拖动的项目.用户可以直接拖

  3. android – 是否有可能通过使用与最初使用的证书不同的证书对其进行签名来发布更新的应用程序

    是否可以通过使用与最初使用的证书不同的证书进行签名来发布Android应用程序的更新?我知道当我们尝试将这样的构建上传到市场时,它通常会给出错误消息.但有没有任何出路,比如将其标记为主要版本,指定市场中的某个地方?解决方法不,你不能这样做.证书是一种工具,可确保您是首次上传应用程序的人.所以总是备份密钥库!

  4. 如何检测Android中是否存在麦克风?

    ..所以我想在让用户访问语音输入功能之前检测麦克风是否存在.如何检测设备上是否有麦克风.谢谢.解决方法AndroidAPI参考:hasSystemFeature

  5. Android – 调用GONE然后VISIBLE使视图显示在错误的位置

    我有两个视图,A和B,视图A在视图B上方.当我以编程方式将视图A设置为GONE时,它将消失,并且它正下方的视图将转到视图A的位置.但是,当我再次将相同的视图设置为VISIBLE时,它会在视图B上显示.我不希望这样.我希望视图B回到原来的位置,这是我认为会发生的事情.我怎样才能做到这一点?编辑–代码}这里是XML:解决方法您可以尝试将两个视图放在RelativeLayout中并相对于彼此设置它们的位置.

  6. android – 获得一首歌的流派

    我如何阅读与歌曲相关的流派?我可以读这首歌,但是如何抓住这首歌的流派,它存放在哪里?解决方法检查此代码:

  7. android – 使用textShadow折叠工具栏

    我有一个折叠工具栏的问题,在展开状态我想在文本下面有一个模糊的阴影,我使用这段代码:用:我可以更改textColor,它可以工作,但阴影不起作用.我为阴影尝试了很多不同的值.是否可以为折叠文本投射阴影?

  8. android – 重用arm共享库

    我已经建立了armarm共享库.我有兴趣重用一个函数.我想调用该函数并获得返回值.有可能做这样的事吗?我没有任何头文件.我试过这个Android.mk,我把libtest.so放在/jni和/libs/armeabi,/lib/armeabi中.此时我的cpp文件编译,但现在是什么?我从objdump知道它的名字编辑:我试图用这个android.mk从hello-jni示例中添加prebuild库:它工作,但libtest.so相同的代码显示以下错误(启动时)libtest.so存在于libhello-j

  9. android – 为NumberPicker捕获键盘’Done’

    我有一个AlertDialog只有一些文本,一个NumberPicker,一个OK和一个取消.(我知道,这个对话框还没有做它应该保留暂停和恢复状态的事情.)我想在软键盘或其他IME上执行“完成”操作来关闭对话框,就像按下了“OK”一样,因为只有一个小部件可以编辑.看起来处理IME“Done”的最佳方法通常是在TextView上使用setonEditorActionListener.但我没有任何Te

  10. android – 想要在调用WebChromeClient#onCreateWindow时知道目标URL

    当我点击一个带有target=“_blank”属性的超链接时,会调用WebChromeClient#onCreateWindow,但我找不到新的窗口将打开的新方法?主页url是我唯一能知道的东西?我想根据目标网址更改应用行为.任何帮助表示赞赏,谢谢!

返回
顶部