我有一个登录界面,成功登录后会显示另一个页面,该页面包含用户信息。我阅读了此贴文和此贴文,还学习了很多如何扩展Application类的知识,但仍无法运行此代码。以下是我的代码,并解释了错误信息。
我使用Volley调用AsyncTask的方法如下:
当我调用startActivity(intent);
时,会出现no activity for token android.os.BinderProxy
这样的错误。我知道这个错误是因为活动被销毁,而Volley响应后的AsyncTask要使用已销毁的上下文,而我不知道如何解决它。
Util.request_function(
activity,
MainActivity.user_session,
key_value,
new VolleyCallback() {
@Override
public void onSuccess(JSONObject result, Context context) {
Activity activity =
MyBaseActivity.myCustomApplication.getCurrentActivity();
Intent intent = new Intent(activity, SelfieCapture.class);
startActivity(intent);
finish();
}
@Override
public void onError(String result) {
}
});
以下是我的接口:
VolleyCallback.java:
public interface VolleyCallback {
void onSuccess(JSONObject result) throws JSONException;
void onError(String result) throws Exception;
}
Util.java
public static void request_function(Context context, CognitoUserSession cognitoUserSession, Map<String, String> key_value, final VolleyCallback callback) {
JSONObject jsonBody = new JSONObject();
CustomJSONObjectRequest postRequest = new CustomJSONObjectRequest(Request.Method.POST,
MainActivity.API_URL,
null,
response -> {
JSONObject jsonObject = (JSONObject) response;
//SoMe Stuff//
callback.onSuccess(null);
}, error -> {
//Log Error//
}){
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
@Override
public Map<String, String> getHeaders() {
final Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return headers;
}
@Override
public byte[] getBody() {
return jsonBody.toString().getBytes();
}
};
// Request added to the RequestQueue
VolleyController.getInstance(context).addToRequestQueue(postRequest);
MyCustomApplication.java
public class MyCustomApplication extends Application {
private Activity mCurrentActivity = null;
public void onCreate() {
super.onCreate();
}
public Activity getCurrentActivity() {
return mCurrentActivity;
}
public void setCurrentActivity(Activity mCurrentActivity) {
this.mCurrentActivity = mCurrentActivity;
}
}
MyBaseActivity.java
public class MyBaseActivity extends Activity {
public static MyCustomApplication myCustomApplication;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myCustomApplication = (MyCustomApplication)this.getApplicationContext();
}
protected void onResume() {
super.onResume();
myCustomApplication.setCurrentActivity(this);
}
protected void onPause() {
clearReferences();
super.onPause();
}
protected void onDestroy() {
clearReferences();
super.onDestroy();
}
private void clearReferences(){
Activity currActivity = myCustomApplication.getCurrentActivity();
if (this.equals(currActivity))
myCustomApplication.setCurrentActivity(null);
}
}