Java Android-使用助手类在Runnable中检索上下文

时间:2018-07-22 06:21:00

标签: java android firebase firebase-cloud-messaging android-context

我正在使用Firebase将消息发送到我的Android应用。 收到此消息后(有效)-我想打开一个AlertDialog

据我到目前为止的了解,接收消息发生在工作线程中,因此我需要再次挂接到主线程中。为此,我用Handler构建了Runnable。 如何在可运行对象中检索我的MainActivity上下文? 我查找了类似Context inside a Runnable

的解决方案

但是,当Firebase发送消息时,MainActivity不是外部类。 这是我的设置

MainActivity

package com.example.xhallix.passamessage;


import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.example.xhallix.passamessage.notifications.FireBaseMessagingServiceManager;
import com.example.xhallix.passamessage.notifications.MyApplication;
import com.example.xhallix.passamessage.notifications.NotificationManager;

public class MainActivity extends AppCompatActivity {

    private static final String LOG_TAG = "CustomLog";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FireBaseMessagingServiceManager fbMessagingService = new FireBaseMessagingServiceManager(this);

    }
}

FireBaseMessagingServiceManager

package com.example.xhallix.passamessage.notifications;

import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.util.Log;


import com.example.xhallix.passamessage.MainActivity;
import com.example.xhallix.passamessage.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import android.os.Handler;

public class FireBaseMessagingServiceManager extends FirebaseMessagingService {

    private static final String LOG_TAG = "CustomLog";

    private Context context;

    public FireBaseMessagingServiceManager(){
        retrieveCurrentToken();
        // this is called when firebase is sending data
    }

    public FireBaseMessagingServiceManager(Context context){
        this.context = context; // this was just a test - this is not called when firebase sends the message again , so this.context will be null in onMessageReceive
    }


    /**
     * Get the Token of GoogleFirebase for that device
     */
    private void retrieveCurrentToken() {
        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                    @Override
                    public void onComplete(@NonNull Task<InstanceIdResult> task) {
                        if (!task.isSuccessful()) {
                            Log.w(LOG_TAG, "getInstanceId failed", task.getException());
                            return;
                        }

                        // Get new Instance ID token
                        String token = task.getResult().getToken();

                        Log.d(LOG_TAG, token);
                    }
                });
    }


    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(LOG_TAG, remoteMessage.getFrom());
        Log.d(LOG_TAG,"Notification Message Body: " + remoteMessage.getNotification().getBody());
        createAlert();
    }


    @Override
    public void onNewToken(String token) {
        Log.d(LOG_TAG, "Refreshed token: " + token);
    }


    protected void createAlert() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                AlertDialog.Builder builder = new AlertDialog.Builder(**???**); // HOW TO RETRIEvE THE CONTEXT FROM MainActivity
                builder.setMessage(R.string.alert_dialog_msg);
                builder.setTitle(R.string.alert_dialog_title);
                builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Log.d(LOG_TAG, "Accepted Dialog");
                    }
                });

                builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Log.d(LOG_TAG, "NOT Accepted Dialog");
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        });
    }
}

1 个答案:

答案 0 :(得分:1)

  

如何在可运行对象中检索我的MainActivity上下文?

您无法获得MainActivity上下文,因为它与您正在运行的服务无关。

如果您真的真的想直接显示该对话框以响应推送通知,则可以显式启动一个以活动为主题的对话框。像这样:

protected void createAlert() {
    startActivity(new Intent(this, DialogThemedActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}