java - 我无法在 onReceive() 中的 onResponse() 之外使用 json 结果 - 改造

标签 java android retrofit2

我是改造新手。 我有 SmsListener 类,它扩展了 Broadcast Receiver 类,该类用于监听消息,当它获取消息时,它将对其执行一些操作。 我正在使用 Retrofit 从本地主机 URL 读取一些 json 数据。 我想从 onResponse 获取 JSON 结果以在 onReceive 中使用它 我定义了一个数组列表来从 onResponse 方法添加 json 值。 但是当我想在 onReceive 中使用这个值时,它给了我 tr_num: null 我不知道为什么会这样。但是当我尝试在 onResponse 中记录 json 值时,它已成功记录。 我正在得到我想要的。但是当我尝试在 onReceive 中使用这个值时,它给了我 tr_num: null 这是我的 SmsListener 类

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;

public class SmsListener extends BroadcastReceiver {

private SharedPreferences sp;

Context context;
String tr_number = "";
RequestQueue requestQueue;

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    this.context = context;

    if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
        Bundle bundle = intent.getExtras();           //---get the SMS message passed in---
        SmsMessage[] msgs = null;
        String msg_from;
        if (bundle != null) {
            //---retrieve the SMS message received---
            try {
                Object[] pdus = (Object[]) bundle.get("pdus");
                msgs = new SmsMessage[pdus.length];
                for (int i = 0; i < msgs.length; i++) {
                    msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                    msg_from = msgs[i].getOriginatingAddress();
                    String msgBody = msgs[i].getMessageBody();

                    Intent intentCall = new Intent(context, MainActivity.class);
                    getTransactionNumber();
                    Log.d("ArrayList ", "ArrayList item 1 = " + tr_num.get(1)); // not Loged out

                    if (msg_from.contains("+249")) {

                        if (msgBody.contains("1435892")) {
                            if (msgBody.contains("50")) {
                                // send Notification to user with success msg

                            }

                        } else {
                            // send Notification to user with error msg
                        }
                    } else {
                        // send Notification to user with DO NOT CHEAT MSG
                    }
                    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentCall, PendingIntent.FLAG_UPDATE_CURRENT);
                    pendingIntent.send();

                }
            } catch (Exception e) {
 //                            Log.d("Exception caught",e.getMessage());
            }
        }
    }
}

private String getAmount(String amount) {


    return "";
}

ArrayList<String> tr_num;

private void getTransactionNumber() {

    RegisterAPI2 registerAPI = ApiClient.getApiClient2().create(RegisterAPI2.class);

    //registerAPI.insertUser(msg, amount, tr_number, phone);
    Call<TrResponse> req = registerAPI.getTrNum();
    req.enqueue(new Callback<TrResponse>() {
                    @Override
                    public void onResponse(Call<TrResponse> call, retrofit2.Response<TrResponse> response) {

                        TrResponse post = response.body();
                        tr_num = new ArrayList<String>();

                        tr_num.add(post.getComment().toString());
                        tr_num.add(post.getTotalCost().toString());

                        Log.d("CallBack", " response is " + post.getComment().toString()); // successfully Loged out
                        Log.d("CallBack", " response is " + tr_num.get(1).toString()); // successfully Loged out
                        //Log.d("CallBack", " response is " + response.toString());

                    }

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

                        Log.d("TTTT CallBack", " Throwable is " + t + " Call  " + call.toString());

                    }

                }
    );

  }
 }

这是我的界面

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;

 public interface RegisterAPI2 {
 // String msg, String phone, String tr_number, String amount
 @GET("getTrNumber.php")
 Call<TrResponse> getTrNum();

 }

这是我的 TrResponse POJO 类

import com.google.gson.annotations.SerializedName;

public class TrResponse {

@SerializedName("Comment")
private String Comment;
@SerializedName("Number_of_people")
private String totalCost;

public String getTotalCost() {
    return totalCost;
}

public void setTotalCost(String totalCost) {
    this.totalCost = totalCost;
}

public TrResponse(String comment, String totalCost) {
    Comment = comment;
    this.totalCost = totalCost;
}

public String getComment() {
    return Comment;
}

public void setComment(String comment) {
    Comment = comment;
}
}

抱歉我的英语不好。 请帮我。 提前致谢。

最佳答案

我在onResponse中进行了操作。 经过 24 小时的搜索,这解决了我的问题。

关于java - 我无法在 onReceive() 中的 onResponse() 之外使用 json 结果 - 改造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50747350/

相关文章:

java - 智能 : Cannot copy resources and compile

java - 如何在 UML 类图中用外部类建模继承?

java - 编辑文本属性不显示日期

android - 如何使用 Retrofit 从 android 发送 FCM 通知?

java - 将日期和时间转换为选定的时区

java - ArrayList未初始化

android - 在智能手机中安装 Android Things 示例代码

java - Android模拟器获取端口号

java - RxAndroid 和 Retrofit : Unable to create call adapter for io. reactivex.Observable<retrofit2.Response<okhttp3.ResponseBody>>

android - Okhttp3,如果为 IP 地址颁发 SSL 证书,则无法验证主机名