混淆将代码放入 AsyncTask [英] confused to put code in AsyncTask

查看:14
本文介绍了混淆将代码放入 AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码来接收聊天消息.但是当我尝试将它放在 AsyncTask 中时我感到困惑.当我将它放入 postexecute 时,我有警告 read cannot beresolution read.readline() .
我想让这段代码在后台工作,以检查是否有任何消息到来.我想问一下,要使代码始终在后台运行,是使用 AsyncTask 还是有其他方法可以做到?
任何人都请帮助我,我很困惑如何制作它.谢谢

I have this code to receive chat messages. but i got confused when i tried to place it in AsyncTask. i have warning read cannot be resolved for read.readline() when i put it in postexecute .
i want to make this code work in background, to check there is any messages coming or not. and i wanna ask, to make the code always running in background is it use AsyncTask or there is any other way to do it?
anyone please help me, i confused how to make it. thank you

接收消息部分

HttpURLConnection connection;
        URL url = null;
        try{
            linkurl = new Koneksi(this);
            SERVER_URL = linkurl.getUrl();
            SERVER_URL += "/mobile/ChatRoom.php?idu="+param2+"&idch="+param3+"&idcm="+param4;
            url = new URL(SERVER_URL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("POST");    

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(SERVER_URL);
            //ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
            //add parameter
                //httpPost.setEntity(new UrlEncodedFormEntity(param));

                HttpResponse httpRespose = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpRespose.getEntity();

                //read content
                InputStream in = httpEntity.getContent();
                BufferedReader read = new BufferedReader(new InputStreamReader(in));
                String msg = "tes";
                while(true)
                {

                    try {
                        msg = read.readLine();
                        Log.d("","MSGGG:  "+ msg);

                        //msgList.add(msg);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.getMessage();
                    }
                    if(msg == null)
                    {
                        break;
                    }
                    else
                    {
                        showMessage(msg, false);
                    }
                }}
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

            }

我尝试过的 AsyncTask 部分 - 已更新但在 getintent() 处收到警告,我必须将这些代码放在哪里?

AsyncTask part that i tried - updated but get warning at getintent() where i must put these codes?

public class ReceivedTask extends AsyncTask<String, String, String> {

    Bundle bundle = this.getIntent().getExtras();
    final String param2 = bundle.getString("keyUserId");
    final String param3 = bundle.getString("keyChatsId");
     String param4 = bundle.getString("keyMessagesId");

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub

        HttpURLConnection connection;
        URL url = null;
        try{
            linkurl = new Koneksi(ChatRoom.this);
            SERVER_URL = linkurl.getUrl();
            SERVER_URL += "/mobile/ChatRoom.php?idu="+param2+"&idch="+param3+"&idcm="+param4;
            url = new URL(SERVER_URL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("POST");    

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(SERVER_URL);
            //ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
            //add parameter
                //httpPost.setEntity(new UrlEncodedFormEntity(param));

                HttpResponse httpRespose = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpRespose.getEntity();

                //read content
                InputStream in = httpEntity.getContent();
                BufferedReader read = new BufferedReader(new InputStreamReader(in));
                String msg = "tes";
                while(true)
                {

                    try {
                        msg = read.readLine();
                        Log.d("","MSGGG:  "+ msg);

                        //msgList.add(msg);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.getMessage();
                    }
                    if(msg == null)
                    {
                        break;
                    }
                    else
                    {
                        showMessage(msg, false);
                    }
                }}
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

            }
    }

ChatRoom.java - 我的完整代码

ChatRoom.java - my full code

public class ChatRoom extends Activity {
    public Koneksi linkurl;
    String SERVER_URL;
    private EditText messageText;
    private TextView meLabel;
    private TextView friendLabel;
    private ViewGroup messagesContainer;
    private ScrollView scrollContainer;
/*    private Handler handler = new Handler();*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chatpage);

        messagesContainer = (ViewGroup) findViewById(R.id.messagesContainer);
        scrollContainer = (ScrollView) findViewById(R.id.scrollContainer);

        Button sendMessageButton = (Button) findViewById(R.id.sendButton);

        Bundle bundle = this.getIntent().getExtras();
        /*final String paramnama = bundle.getString("nama");*/
        messageText = (EditText) findViewById(R.id.messageEdit);
        meLabel = (TextView) findViewById(R.id.meLabel);
        friendLabel = (TextView) findViewById(R.id.friendLabel);
        meLabel.setText("me");


        final String param1 = bundle.getString("keyCourseId");
        final String param2 = bundle.getString("keyUserId");
        final String param3 = bundle.getString("keyChatsId");
         String param4 = bundle.getString("keyMessagesId");


        sendMessageButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
                postParameters.add(new BasicNameValuePair("messages", messageText.getText().toString()));

                String response = null;

                try {
                    linkurl = new Koneksi(ChatRoom.this);
                    SERVER_URL = linkurl.getUrl();
                    SERVER_URL += "/mobile/ChatKirimTeks.php?idu="+param2+"&idch="+param3;
                   response = CourseHttpClient.executeHttpPost(SERVER_URL, postParameters);

                   String res = response.toString();

                   res = res.trim();

                   res = res.replaceAll("\s+","");
                   if(res.equals("1")){
                       String messageString = messageText.getText().toString();
                       showMessage(messageString, true);
                       messageText.getText().clear();
                   }else
                   {
                       createDialog("Maaf", "Messages Anda Gagal Terkirim");
                   }
                }

                catch (Exception e) {

                    messageText.setText(e.toString());  

                }

             }

        });


        HttpURLConnection connection;
        URL url = null;
        try{
            linkurl = new Koneksi(this);
            SERVER_URL = linkurl.getUrl();
            SERVER_URL += "/mobile/ChatRoom.php?idu="+param2+"&idch="+param3+"&idcm="+param4;
            url = new URL(SERVER_URL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("POST");    

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(SERVER_URL);
            //ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
            //add parameter
                //httpPost.setEntity(new UrlEncodedFormEntity(param));

                HttpResponse httpRespose = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpRespose.getEntity();

                //read content
                InputStream in = httpEntity.getContent();
                BufferedReader read = new BufferedReader(new InputStreamReader(in));
                String msg = "tes";
                while(true)
                {

                    try {
                        msg = read.readLine();
                        Log.d("","MSGGG:  "+ msg);

                        //msgList.add(msg);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.getMessage();
                    }
                    if(msg == null)
                    {
                        break;
                    }
                    else
                    {
                        showMessage(msg, false);
                    }
                }}
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

            }


    public class ReceivedTask extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected String doInBackground(String... arg0) {
            // TODO Auto-generated method stub
            HttpURLConnection connection;
            URL url = null;
            try{
                linkurl = new Koneksi(ChatRoom.this);
                SERVER_URL = linkurl.getUrl();
                SERVER_URL += "/mobile/ChatRoom.php?idu="+param2+"&idch="+param3+"&idcm="+param4;
                url = new URL(SERVER_URL);
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setRequestMethod("POST");    

                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(SERVER_URL);
                //ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
                //add parameter
                    //httpPost.setEntity(new UrlEncodedFormEntity(param));

                    HttpResponse httpRespose = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpRespose.getEntity();

                    //read content
                    InputStream in = httpEntity.getContent();
                    BufferedReader read = new BufferedReader(new InputStreamReader(in));
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }

        }
        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            String msg = "tes";
            while(true)
            {

                try {
                    msg = read.readLine();
                    Log.d("","MSGGG:  "+ msg);

                    //msgList.add(msg);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.getMessage();
                }
                if(msg == null)
                {
                    break;
                }
                else
                {
                    showMessage(msg, false);
                }
            }
        }
    }

    public void showMessage(String message, boolean leftSide) {
        final TextView textView = new TextView(ChatRoom.this);
        textView.setTextColor(Color.BLACK);
        textView.setText(message);

        int bgRes = R.drawable.left_message_bg;

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        if (!leftSide) {
            bgRes = R.drawable.right_message_bg;
            params.gravity = Gravity.RIGHT;
        }

        textView.setLayoutParams(params);

        textView.setBackgroundResource(bgRes);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                messagesContainer.addView(textView);

                // Scroll to bottom
                if (scrollContainer.getChildAt(0) != null) {
                    scrollContainer.scrollTo(scrollContainer.getScrollX(), scrollContainer.getChildAt(0).getHeight());
                }
                scrollContainer.fullScroll(View.FOCUS_DOWN);
            }
        });
    }

    private void createDialog(String title, String text) {
        AlertDialog ad = new AlertDialog.Builder(this)
        .setPositiveButton("Ok", null)
        .setTitle(title)
        .setMessage(text)
        .create();
        ad.show();
    }
}

推荐答案

您收到错误消息 read cannot beresolution 因为 Android 禁止您从用户界面线程访问 Internet.您必须在后台线程中执行此操作.事实上,使用 AsyncTask 的目的是让用户界面线程尽可能自由.

You're getting the error message read cannot be resolved because Android forbids you to access the internet from the User Interface thread. You have to do that in a background thread. Indeed, the point of using AsyncTask is to keep the user interface thread as free as possible.

每当我使用AsyncTask 时,我通常会创建一个类来保存任务的所有参数,并创建另一个类来保存结果.此外,我确保结果类可以表示可能发生的任何错误条件,例如抛出的异常.所以我使用的通用模板看起来像这样(注意:这是在不需要进度报告时使用的).

Whenever I use AsyncTask, I usually create a class to hold all the parameters of the task, and another class to hold the results. Also, I make sure that the results class can represent any error conditions that may occur, e.g. exceptions thrown. So the general template that I use looks something like this (NB: this is for when a progress report isn't required).

public class MyActivity extends Activity {

    static class MyAsyncTaskParameters {
        // put all the parameters that the task will need here
    }

    void KickOffAsynctask(...) {  // various arguments as required by the task in hand
        MyAsyncTaskParameters params = new MyAsyncTaskParameters(...);  // package up all the parameters
        MyAsyncTask newtask = new MyAsyncTask();
        newtask.execute(params);
    }

    static class MyAsyncTaskResults {
        // put all the results that the task can generate here
        // NOTE: errors can occur in tasks, also exceptions
        //       can be thrown in tasks, so make it possible
        //       for this class to describe all error conditions that can occur
    }

    static class MyAsyncTask extends AsyncTask<MyAsyncTaskParameters, Void, MyAsyncTaskResults> {

        @Override
        protected MyAsyncTaskResults doInBackground(MyAsyncTaskParameters... params) {
            MyAsyncTaskResults results = new MyAsyncTaskResults();
            try {
                MyAsyncTaskParameters taskParameters = params[0];
                // This method will run in a background thread, so
                // do as much as possible of the AsyncTask here.
            } catch (Throwable e) {
                // Set results object to indicate that an exception occurred.
            }
            return results;
        }

        @Override
        protected void onPostExecute(MyAsyncTaskResults res) {
            // This method will run in the User Interface thread.
            // Use it to deal with the results stored in res.
            // If an error has occurred, the res object will have it stored
            // so take appropriate action, e.g. report to user.
        }

    }

}

这篇关于混淆将代码放入 AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆