AsyncTask获取String值输出并存储在mainthread变量中

时间:2017-05-26 02:11:25

标签: java android android-asynctask

我想从AsyncTask获取字符串值输出。并将其存储在主线程中的变量中。我怎么能这样做?

我尝试store = new ReceiveData().execute().get(),但它会抛出执行异常错误。但无论如何,我的问题不是关于执行异常错误。我只需要一种方法来取出字符串,请帮忙!

这是我的活动代码:

public class MainActivity extends AppCompatActivity {  //MAIN ACTIVITIES (REMOTE)

double multiplier;
int seekbarvalue, finallumens;

@Override
protected void onCreate(Bundle savedInstanceState) {
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); //On orientation change socket will disconnect...
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //Toast.makeText(MainActivity.this, LoginActivity.SERVER_IP, Toast.LENGTH_LONG).show();


    //================START AFTER DEFAULT ON CREATE=================
    SeekBar seekbarbrightness = (SeekBar) findViewById(R.id.seekbarbrightness);
    final TextView tblumens, tbvolts, tbamps;

    tblumens = (TextView) findViewById(R.id.tblumens);
    seekbarvalue = seekbarbrightness.getProgress();
    multiplier = (double) seekbarvalue / 100;
    finallumens = (int) (multiplier * LoginActivity.enterlumens);
    tblumens.setText(String.valueOf(finallumens) + " Lumens");

    tbvolts = (TextView) findViewById(R.id.tbvolts);
    tbamps = (TextView) findViewById(R.id.tbamps);

    seekbarbrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekbarbrightness, int progress, boolean b) {
            if (b == true) {
                seekbarvalue = seekbarbrightness.getProgress();
                multiplier = (double) seekbarvalue / 100;
                finallumens = (int) (multiplier * LoginActivity.enterlumens);
                tblumens.setText(String.valueOf(finallumens) + " Lumens");
                if (LoginActivity.getSocket() != null) {
                    try {
                        LoginActivity.getSocket().getOutputStream().write(String.valueOf(multiplier).getBytes());
                        new ReceiveData().execute();
                        //infinite loop here to keep receiving volts and amperes.
                        //Do a split and assign value to volt and amp
                        //String[] strrecv= store.split("|");
                        //String volts = strrecv[0];
                        //String amps = strrecv[1];
                        //tbvolts.setText("Voltage: " + volts + " V");
                        //tbamps.setText("Amperes:" + amps + " A");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                } else {
                    Toast.makeText(MainActivity.this, "NOT connected To Socket, please disconnect and reconnect!", Toast.LENGTH_SHORT).show();
                }
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });




}

在我Asynctask我正在做这件事。

class ReceiveData extends AsyncTask<Void, Void, String> {
    String str;
    protected String doInBackground(Void... args) {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(LoginActivity.getSocket().getInputStream()));
            str = in.readLine();
            return str;

        } catch (IOException e) {
            e.printStackTrace();
            String str = "fail";
            return str;
        }

    }

    protected void onPostExecute(String str) {
        //super.onPostExecute(str);
    }

}

1 个答案:

答案 0 :(得分:2)

AsyncTask的目的是在单独的线程中执行异步任务以释放主线程并避免UX问题。为了您的目的,我建议在AsyncTask内转移try块内的所有工作,并在执行后更新UI。

像这样的东西

在MainThread中

new ReceiveData().execute();

在AsyncTask中

class ReceiveData extends AsyncTask<Void, Void, Boolean> {
    String volts;
    String amps;

    protected Boolean doInBackground(Void... args) {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(LoginActivity.getSocket().getInputStream()));
            str = in.readLine();
            String[] strrecv= store.split("|");
            volts = strrecv[0];
            amps = strrecv[1];
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    protected void onPostExecute(Boolean result) {
        if (result) {
            tbvolts.setText("Voltage: " + volts + " V");
            tbamps.setText("Amperes:" + amps + " A");
        }
    }
}

请注意,这仅适用于您的“活动”中定义AsyncTask的情况。如果没有,您需要从AsyncTask创建一个界面并在您的活动中实施它并激活它onPostExecute