Android中的Firebase推送通知无法正常工作

时间:2017-08-29 22:19:57

标签: android firebase notifications firebase-notifications

我正在尝试向我的应用程序添加firebase推送通知服务我按照firebase文档中的所有步骤进行操作,但是当我尝试发送通知时我失败了,我的手机没有收到任何通知,请有人帮我解决这个问题。 build.gradle(app)

android {
    //...
    }
    buildTypes {
        release {
            //..
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    .....
    //notifications
    compile 'com.google.firebase:firebase-core:10.2.1'
    compile 'com.google.firebase:firebase-messaging:10.2.1'
    compile 'com.firebase:firebase-jobdispatcher:0.5.2'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

的build.gradle

dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }

清单

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="maa.g">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <application
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <meta-data  android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@mipmap/ic_launcher" />
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorPrimary" />
        <!-- [END fcm_default_icon] -->

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

FirebasePushNotifications

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "MyFirebaseMsgService";
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

            if (/* Check if data needs to be processed by long running job */ true) {
                // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
                scheduleJob();
            } else {
                // Handle message within 10 seconds
                handleNow();
            }

        }
            if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

    }
    private void scheduleJob() {
        FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
        Job myJob = dispatcher.newJobBuilder()
                .setService(MyJobService.class)
                .setTag("my-job-tag")
                .build();
        dispatcher.schedule(myJob);
    }
    public class MyJobService extends JobService {
        @Override
        public boolean onStartJob(JobParameters job) {

            return false; 
        }

        @Override
        public boolean onStopJob(JobParameters job) {
            return false; 
        }
    }
    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }

    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.mipmap.ic_launcher)
                .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());
    }
}

2 个答案:

答案 0 :(得分:0)

我认为您在清单文件的服务部分缺少此部分:

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

课程应该是这样的:

 package <your project package signature>;

 import com.google.firebase.iid.FirebaseInstanceId;
 import com.google.firebase.iid.FirebaseInstanceIdService;

 public class ProjectFirebaseInstanceIDService extends FirebaseInstanceIdService 
 {
     @Override
     public void onTokenRefresh() {
          super.onTokenRefresh();

          String refreshedToken = FirebaseInstanceId.getInstance().getToken();

         sendRegistrationToServer(refreshedToken);
     }

    private void sendRegistrationToServer(String token) {
         // Add your implementation for notification purposes
     }
 }

您需要将消息发送到订阅主题的设备或设备组或设备。

详情请见link

答案 1 :(得分:0)

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();

@Override
public void onTokenRefresh() {
    super.onTokenRefresh();
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();

    Log.d(TAG,"New Token"+ refreshedToken);
}

}

使用此服务并将此服务添加到清单

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