单击Android通知时打开对话活动

时间:2020-07-15 22:46:00

标签: android firebase push-notification firebase-cloud-messaging retrofit

**我在聊天中得知,当应用程序在后台运行时,它可以完美地接收到通知,但是当我单击时,它将打开主菜单。

也许清单上有事要做。**

Mnifest.xml

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

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

    <application
        android:allowBackup="true"
        android:hardwareAccelerated="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning">
        <activity android:name=".Nuevo_mensaje_Activity"
            android:parentActivityName=".MenuActivity">
        </activity>
        <activity android:name=".InfoChatActivity" />
        <activity android:name=".ComentsActivity" />
        <activity android:name=".PersonProfileActivity" />
        <activity android:name=".ChatActivity"/>
        <activity android:name=".ProfileActivity"
            android:parentActivityName=".MenuActivity"/>
        <activity android:name=".ProductDetailsActivity" />
        <activity
            android:name=".SettinsActivity"
            android:parentActivityName=".MenuActivity" />
        <activity
            android:name=".MenuActivity"
            android:label="@string/title_activity_menu"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".addnewcategoryActivity"
            android:windowSoftInputMode="adjustPan|stateHidden"
            android:parentActivityName=".CategoryActivity"/>
        <activity android:name=".CategoryActivity"
            android:parentActivityName=".MenuActivity"/>
        <activity
            android:name=".Fragmentos.InstruccionesActivity"
            android:label="@string/title_activity_instrucciones"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity android:name=".login" />
        <activity android:name=".MainActivity" />
        <activity android:name=".Marche">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
            android:theme="@style/Base.Theme.AppCompat" />

        <service
            android:name=".Notificaciones.MyFirebaseMessaging"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>


    </application>

</manifest>

我希望打开发送消息的用户的对话

MyFirebaseMessaging.java

public class MyFirebaseMessaging extends FirebaseMessagingService {
    private static final String TAG = "FirebaseIntent";
    @Override
    public void onNewToken(@NonNull String s) {
        super.onNewToken(s);

        FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        String refreshToken = FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken();

        if (firebaseUser != null) {
            updateToken(refreshToken);
        }
    }

    private void updateToken(String refreshToken) {
        FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();

        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Tokens");
        Token token = new Token(refreshToken);
        reference.child(firebaseUser.getUid()).setValue(token);
    }

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
       

        Map<String, String> data_notify = remoteMessage.getData();

        //String sented=remoteMessage.getData().get("sented");
        user = remoteMessage.getData().get("user");
        Log.d(TAG, "Message data payload: " + user);

        SharedPreferences preferences  = getSharedPreferences("PREFS", MODE_PRIVATE);
        String currentUser = preferences.getString("currentuser", "none");

        FirebaseUser firebaseUser= FirebaseAuth.getInstance().getCurrentUser();

        //String click_action = remoteMessage.getNotification().getClickAction();

        if (firebaseUser != null && data_notify.size() > 0)
        {
            if (!currentUser.equals(user))
            {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                {
                    sendOreoNotification(remoteMessage);
                } else {
                    sendNotification(remoteMessage);
                }
            }
        }

    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    private void sendOreoNotification(RemoteMessage remoteMessage){
        String user = remoteMessage.getData().get("user");
        String icon = remoteMessage.getData().get("icon");
        String title = remoteMessage.getData().get("title");
        String body = remoteMessage.getData().get("body");

        RemoteMessage.Notification notification=remoteMessage.getNotification();
        int j = Integer.parseInt(user.replaceAll("[\\D]", ""));

        Intent intent = new Intent(this, Nuevo_mensaje_Activity.class);

        Bundle bundle=new Bundle();
        bundle.putString("userid", user);
        intent.putExtras(bundle);
        Log.d(TAG, "Message data payload: " + user);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent=PendingIntent.getActivity(this, j,intent,PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        OreoNotification oreoNotification = new OreoNotification(this);
        Notification.Builder builder = oreoNotification.getOreoNotification(title,body,pendingIntent,
                defaultSound,icon);
        int i=0;
        if(j>0){
            i=j;
        }
        oreoNotification.getManager().notify(i,builder.build());

    }

    private void sendNotification(RemoteMessage remoteMessage) {
        String user = remoteMessage.getData().get("user");
        String icon = remoteMessage.getData().get("icon");
        String title = remoteMessage.getData().get("title");
        String body = remoteMessage.getData().get("body");

        RemoteMessage.Notification notification=remoteMessage.getNotification();

        int j = Integer.parseInt(user.replaceAll("[\\D]", ""));

        Intent intent = new Intent(this, Nuevo_mensaje_Activity.class);
        Bundle bundle=new Bundle();
        bundle.putString("userid", user);
        intent.putExtras(bundle);

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent=PendingIntent.getActivity(this,j,intent,PendingIntent.FLAG_ONE_SHOT);

        Log.d(TAG,"NEW_INTENT: "+user);

        Uri defaultSound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(Integer.parseInt(icon))
                .setContentTitle(title)
                .setContentText(body)
                .setAutoCancel(true)
                .setSound(defaultSound)
                .setContentIntent(pendingIntent);
        NotificationManager noti=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

        int i=0;
        if(j>0){
            i=j;
        }
        noti.notify(i,builder.build());




    }
}

我有另一项活动,发送了第一条消息,可能是造成问题的原因

ChatActivity.java

private void sendNotification(String receiver, final String username, final String message)
    {
        DatabaseReference tokens=FirebaseDatabase.getInstance().getReference("Tokens");
        Query query=tokens.orderByKey().equalTo(receiver);
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot snapshot: dataSnapshot.getChildren()){
                    Token token=snapshot.getValue(Token.class);
                    Data data =new Data(fuser.getUid(),R.drawable.logo_peque,username+": "+message, "Nuevo Mensaje",messageReceicverID);

                    Sender sender=new Sender(data, token.getToken());
                    apiService.sendNotification(sender)
                            .enqueue(new Callback<MyResponse>() {
                                @Override
                                public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
                                    if(response.code()==200){
                                        if(response.body().success!=1){
                                            Toast.makeText(ChatActivity.this, "!Fallo¡", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }

                                @Override
                                public void onFailure(Call<MyResponse> call, Throwable t) {

                                }
                            });

                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });

    }

没有答案可以帮助我,我已经尝试了所有方法,希望有人可以帮助我。

0 个答案:

没有答案