无法呼叫处理程序

时间:2016-12-06 10:43:00

标签: android okhttp3

我正试图在服务器点击按钮时执行注销操作,但每当我点击Logout时,它就会卡在SweetAlertDialogBox上。

当我调试我的代码时,调试器调试代码直到行:“client.newCall(request).enqueue(new callback(){”在logoutservice()内部,然后在此之后转到“String message” “它实际上终止了。它会在失败和onResponse方法上跳过它们

Logcat中没有提到错误

这是我的按钮点击代码: -

 btnLogout = itemBuilder.setContentView(logoutIcon).build();
    btnLogout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlarmActivity.this);
            alertDialog.setMessage("Are you sure you want to log out?");
            alertDialog.setCancelable(false);
            alertDialog.create();
            alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    if (networkUtil.isConnected()) {
                        logoutService();
                    } else {
                        AlertDialog.Builder alertbox = new AlertDialog.Builder(AlarmActivity.this);
                        alertbox.setMessage("No network connection, Please try after some time");
                        alertbox.create();
                        alertbox.setCancelable(false);
                        alertbox.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
    }
                        });
                        alertbox.show();
                    }
                }

            }).setNegativeButton("No", null).show();

        }
    });

这是我的退出和退出服务方法: -

    public void logout() {
    Intent i = new Intent(this, AlertDialogActivity.class);
    pendingIntent = PendingIntent.getActivity(AlarmActivity.this,
            12345, i, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    manager.cancel(pendingIntent);
    stopService(new Intent(AlarmActivity.this, LocationTracker.class));
    System.exit(0);
}

  private void logoutService() {
    OkHttpClient client = new OkHttpClient();
    String requestURL = String.format(getResources().getString(R.string.service_logout));
    JSONObject jsonrequest = new JSONObject();
    try {
        Date today = Calendar.getInstance().getTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        jsonrequest.accumulate("mobNo", pref.getValueFromSharePref("mobileno"));
        jsonrequest.accumulate("empAuthKey", pref.getValueFromSharePref("authKey"));
        jsonrequest.accumulate("logoutTime", simpleDateFormat.format(today));
        jsonrequest.accumulate("lat", "" + locationInfo.lastLat);
        jsonrequest.accumulate("lon", "" + locationInfo.lastLong);
    } catch (Exception e) {
        e.printStackTrace();
    }
    final RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonrequest.toString());
    Request request = new Request.Builder()
            .url(requestURL)
            .post(body).build();

    final SweetAlertDialog pDialog = new SweetAlertDialog(AlarmActivity.this, cn.pedant.SweetAlert.SweetAlertDialog.PROGRESS_TYPE);
    pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
    pDialog.setTitleText("Loading, Please wait ...");
    pDialog.setCancelable(false);
    pDialog.show();

    client.newCall(request).enqueue(new Callback() {
        String status,message;
        Handler handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == 1) {
                    Toast.makeText(getBaseContext(), "" + message, Toast.LENGTH_SHORT).show();
                    logout();
                } else if (msg.what == 0) {
                    Toast.makeText(getBaseContext(), "" + message, Toast.LENGTH_SHORT).show();
                } else if (msg.what == -1) {
                    Toast.makeText(getBaseContext(), "" + message, Toast.LENGTH_SHORT).show();
                } else if (msg.what == 2) {
                    Toast.makeText(AlarmActivity.this, "System Error Please try again...", Toast.LENGTH_LONG).show();
                }
                return false;
            }
        });

        @Override
        public void onFailure(Call call, IOException e) {
            if (pDialog.isShowing()) pDialog.dismiss();
            handler.sendEmptyMessage(2);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                String responseString = response.body().string();
                try {
                    JSONObject jsonResponse = new JSONObject(responseString);
                    status = jsonResponse.getString("status");
                    message = jsonResponse.getString("message");

                    if (status.equals("success")) {
                        if (pDialog.isShowing()) pDialog.dismiss();
                        handler.sendEmptyMessage(1);
                        response.body().close();

                    } else if (status.equals("failure")) {
                        if (pDialog.isShowing()) pDialog.dismiss();
                        handler.sendEmptyMessage(-1);
                        response.body().close();

                    } else if (status.equals("error")) {
                        if (pDialog.isShowing()) pDialog.dismiss();
                        handler.sendEmptyMessage(0);
                        response.body().close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if (pDialog.isShowing()) pDialog.dismiss();
                    handler.sendEmptyMessage(2);
                    response.body().close();
                }
            }
        }
    });
}

请帮我解决这个问题,Logcat没有错误..

1 个答案:

答案 0 :(得分:1)

您可能在Handler内使用onResponse在UI线程中执行某些操作,因此您还应该在handleMessage中解除SweetAlertDialog

Handler handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
 //...
                if (pDialog.isShowing()) pDialog.dismiss();
                return false;
            }
        });