应用程序处于活动状态时,用firebase推动通知不起作用



首先对我的英语不好后悔。

我正在处理正确运行的Android应用程序。但是,在使用Firebase接收推送通知时,我有问题。与其他提问的问题相反,我的设备在应用程序在后台或停止时正确地收到了推送通知。但是,如果应用程序打开并使用。

,我没有收到通知。

这是我的代码:

subtest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:name=".app.FirebaseLoader"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/NoActionBar"
        android:supportsRtl="true">
        <activity
        ...
        </activity>
        <service android:name=".app.NotificationListener"/>
    </application>
</manifest>

NotificationListener类:

public class NotificationListener extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    //When the service is started
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //Opening sharedpreferences
        SharedPreferences sharedPreferences = getSharedPreferences(Constants.SHARED_PREF, MODE_PRIVATE);
        //Getting the firebase id from sharedpreferences
        String id = sharedPreferences.getString(Constants.UNIQUE_ID, null);
        //Creating a firebase object
        Firebase firebase = new Firebase(Constants.FIREBASE_APP + id);
        //Adding a valueevent listener to firebase
        //this will help us to  track the value changes on firebase
        firebase.addValueEventListener(new ValueEventListener() {
            //This method is called whenever we change the value in firebase
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                //Getting the value from firebase
                //We stored none as a initial value
                String msg = snapshot.child("msg").getValue().toString();
                String title = snapshot.child("title").getValue().toString();
                //So if the value is none we will not create any notification
                if (msg.equals("none"))
                    return;
                //If the value is anything other than none that means a notification has arrived
                //calling the method to show notification
                //String msg is containing the msg that has to be shown with the notification
                showNotification(title, msg);
            }
            @Override
            public void onCancelled(FirebaseError firebaseError) {
                Log.e("The read failed: ", firebaseError.getMessage());
            }
        });
        return START_STICKY;
    }

    private void showNotification(String title, String msg){
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://autofreunde-isartal.de"));
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        builder.setContentIntent(pendingIntent);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setContentTitle(title);
        builder.setContentText(msg);
//        builder.setSound();
        builder.setLights(Color.GREEN, 500, 300);
        builder.setDefaults(Notification.DEFAULT_VIBRATE);
        builder.setOngoing(true);
        builder.setWhen(System.currentTimeMillis());
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(1, builder.build());
    }
}

firbaseloader class

public class FirebaseLoader extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Firebase.setAndroidContext(this);
    }
}

主activity类:

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
... (fragment loading method) ...
    if (!isRegistered()) {
        registerDevice();
    } else {
            startService(new Intent(getApplicationContext(), NotificationListener.class));
            Toast.makeText(getApplicationContext(), "service started", Toast.LENGTH_LONG).show();
    }
}
private boolean isRegistered() {
    SharedPreferences sharedPreferences = getSharedPreferences(Constants.SHARED_PREF, MODE_PRIVATE);
    return sharedPreferences.getBoolean(Constants.REGISTERED, false);
}
private void registerDevice() {
    //Creating a firebase object
    Firebase firebase = new Firebase(Constants.FIREBASE_APP);
    //Pushing a new element to firebase it will automatically create a unique id
    Firebase newFirebase = firebase.push();
    //Creating a map to store name value pair
    Map<String, String> val = new HashMap<>();
    //pushing msg = none in the map
    val.put("msg", "none");
    val.put("title", "none");
    //saving the map to firebase
    newFirebase.setValue(val);
    //Getting the unique id generated at firebase
    String firebaseId = newFirebase.getKey();
    //Finally we need to implement a method to store this unique id to our server
    sendIdToServer(firebaseId);
}
private void sendIdToServer(final String firebaseId) { }

(在MainActivity i实现了4个片段,您可以按菜单进行选择(

我希望有人可以帮助我找到这个错误。感谢您的回答。

您的清单内是否可能缺少某些声明?

        <service android:name=".notification.MessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".notification.InstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

因此,您是否实施了所有相关类?

来源:https://firebase.google.com/docs/cloud-messaging/android/client/client

最新更新