【问题标题】:Call asynctask in handler在处理程序中调用 asynctask
【发布时间】:2014-05-06 19:25:03
【问题描述】:

我试图每 1 秒调用一次处理程序内部的 AsyncTask,但我不断收到 RuntimeException。有人知道如何解决这个问题吗? 以下是我的代码:

package com.example.whatsapp;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends ActionBarActivity {

    Intent contacts;
    EditText t;
    int counter=0;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        public void run() {
            new AsyncReceiveMessage().execute();
            //afficher();
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        contacts = new Intent(this, ContactsList.class);
        runnable.run();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void afficher()
    {
        counter+=1;
        System.out.println("Hello " +counter);
        handler.postDelayed(runnable, 1000);
    }

    public void registerUser(View view)
    {
        t = (EditText) findViewById(R.id.editText1);
        Button b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(t.getText().length()==11)
                {
                    Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_LONG).show();
                    contacts.putExtra("deviceNumber", t.getText().toString());
                    startActivity(contacts);
                    new AsyncRegister().execute();
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Check you number again", Toast.LENGTH_LONG).show();
                }
            }
        });

    }

    private class AsyncRegister extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            t = (EditText) findViewById(R.id.editText1);
            ServerAPI.registerUser(t.getText().toString());
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }

    private class AsyncReceiveMessage extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            ServerAPI.receiveMessage(t.getText().toString());
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }

}

【问题讨论】:

  • 请不要在这里倾倒你的整个项目。仅发布相关代码,并提供堆栈跟踪。此外,显示抛出异常的行。

标签: android android-asynctask handler


【解决方案1】:

当您在AsyncTaskdoInBackground 方法中访问主线程时:

@Override
protected String doInBackground(String... params) {
    ServerAPI.receiveMessage(t.getText().toString());
    return "Executed";
}

如果您在doInBackground 中注释第一行代码,是否会收到错误消息? 避免这种情况,并尝试在onPreExecutedoInBackground作为paramsString 参数或传递给AsyncTask 构造函数之前获取这些值。

【讨论】:

  • 当我评论该行时,它可以正常工作。该行负责创建发布请求并从服务器获取一些数据。
  • 好吧,如果您只是在该方法中硬编码 EditTextBox 的文本会发生什么?例如ServerAPI.receiveMessage("WriteHereWhatTextBoxHas"); 有用吗?
  • 函数没有被调用。太奇怪了
  • 这可能是另一个不同的问题,我们不知道 ServerAPI 在里面做了什么。您提出的问题可以很容易地解决,避免访问那里的主线程。获取之前EditTextBox的文本并通过doInBackground(String... params),然后与ServerAPI.receiveMessage(params[0]);一起使用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-04
  • 2011-04-06
  • 2013-08-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多