繁体   English   中英

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

[英]Java Android - retrieve context inside runnable using a helper class

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

从到目前为止的了解,接收消息发生在工作线程中,因此我需要再次挂接到主线程中。 为此,我使用Runnable构建了Handler 如何在MainActivity中检索我的MainActivity上下文? 在Runnable中查找了像Context这样的解决方案

但是,当Firebase发送消息时, 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();
            }
        });
    }
}

如何在Runnable中检索我的MainActivity上下文?

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

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

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

暂无
暂无

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

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