我有一个使用处理程序的可运行间隔,它控制我的 Volley 请求:
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
//Volley request...
AppController.getInstance().addToRequestQueue(volleyreq);
handler.postDelayed(this, 5000);
}
};
handler.postDelayed(runnable, 5000);
我需要在用户按下后退按钮并确认对话框时停止我的请求。这会停止我的位置更新、“检查”用户并切换到 CheckinActivity
。我能否在此时以某种方式插入 removeCallbacks()
方法,或者它究竟会去哪里?
onBackPressed()
:
//Checking Out With Back Button
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Checking Out!");
alertDialogBuilder.setMessage("Are you sure you want to check out?");
alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Inserting here crashes app after pressing back button
handler.removeCallbacks(runnable);
//Disconnects from location updates...
mGoogleApiClient.disconnect();
//Fires a volley POST request...
checkout();
Intent intent=new Intent(OrderListActivity.this,CheckinActivity.class);
startActivity(intent);
OrderListActivity.this.finish();
}
});
alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
我试过从不同的地方触发它,但它总是让我的应用程序崩溃并给我一个空指针异常。
崩溃日志:
08-20 19:41:08.540 2815-2815/com.myapp.workingprojectlocal E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myapp.workingprojectlocal, PID: 2815
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.Handler.removeCallbacks(java.lang.Runnable)' on a null object reference
at com.myapp.workingprojectlocal.OrderListActivity$12.onClick(OrderListActivity.java:394)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:161)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
最佳答案
这意味着您的处理程序是 NULL
。这样做:
if (handler !=null && runnable !=null)
handler.removeCallbacks(runnable);
它应该可以解决您的问题。
关于Android 停止 Runnable onBackPressed(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45787992/