异步功能不适用于Android

异步功能不适用于Android

我希望用户从应用程序注销后,其状态应为离线。我在注销菜单中写了以下语句-

else if (id == R.id.nav_lout) {
        status = "Offline";
        mAuthTask = new UserLoginTask();
        mAuthTask.execute((Void) null);

        new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("MyApp")
                .setMessage("Are you sure?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        session.logoutUser();
                    }
                }).setNegativeButton("No", null).show();
    }


现在的问题是警报框正在显示,并且用户也已注销。但是他的状态在数据库中仍然是ONLINE。

status = "Offline";
    mAuthTask = new UserLoginTask();
    mAuthTask.execute((Void) null);


这部分没有执行。请帮助。

UserLoginTask类的代码-

    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
    UserLoginTask() {
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        InputStream is = null;
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("email", uEmailID));
        nameValuePairs.add(new BasicNameValuePair("status", status));

        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://mywebsite.com/Android/checkIsOnline.php");
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpClient.execute(httpPost);

            HttpEntity entity = response.getEntity();

            is = entity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            result = sb.toString().trim();

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        mAuthTask = null;
    }

    @Override
    protected void onCancelled() {
        mAuthTask = null;
    }
}

最佳答案

您应该在警报对话框onclick中调用此AsyncTask,将execute()更改为.executeOnExecutor()。然后检查您的onpreexecute和doInBackground是否工作。

关于php - 异步功能不适用于Android,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46442532/

10-09 06:36