简体   繁体   English

应用处于活动状态时,带有Firebase的推送通知不起作用

[英]Push Notification with Firebase not working while app is active

First of all sorry for my bad english. 首先,抱歉我的英语不好。

I'm working on an Android App which functions correctly. 我正在使用可正常运行的Android应用。 However, I have a problem when receiving push notifications using Firebase. 但是,使用Firebase接收推送通知时出现问题。 Contrary to other asked questions, my device correctly receives push notifications while the App is in the background or stopped. 与其他询问相反,当应用程序在后台或停止运行时,我的设备可以正确接收推送通知。 I do not receive notification, however, if the app is open and in use. 但是,如果该应用程序已打开且正在使用中,则不会收到通知。

Here is my code: 这是我的代码:

Manifest.xml: 的Manifest.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 class: 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());
    }
}

FirebaseLoader class FirebaseLoader类

public class FirebaseLoader extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        Firebase.setAndroidContext(this);
    }
}

MainActivity class: MainActivity类:

@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) { }

(in MainActivity I implemented 4 fragments, you can select by menu) (在MainActivity中,我实现了4个片段,可以通过菜单选择)

I hope someone can help me find this error. 希望有人可以帮助我找到此错误。 Thanks for answer. 感谢您的回答。

Is it possible that you're missing certain declarations inside your manifest? 您是否可能在清单中缺少某些声明?

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

Therefore have you implemented all the relevant classes? 因此,您实现了所有相关的类吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM