
我有此代码来接收聊天消息.但是当我尝试将其放入AsyncTask时感到困惑.我将警告信息读入postexecute时无法解析为read.readline().
我想使此代码在后台运行,以检查是否有任何消息.我想问一下,要使代码始终在后台运行,是使用AsyncTask还是有其他方法做到这一点?
任何人都请帮助我,我感到困惑.谢谢
接收消息部分
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()处收到警告,我必须在其中放置这些代码?
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-我的完整代码
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(); }}解决方法:
您收到的错误消息无法解决,因为AndroID禁止您从用户界面线程访问互联网.您必须在后台线程中执行此 *** 作.的确,使用AsyncTask的目的是使用户界面线程尽可能地自由.
每当我使用AsyncTask时,通常都会创建一个类来保存任务的所有参数,并创建另一个类来保存结果.另外,我确保结果类可以代表可能发生的任何错误情况,例如引发异常.因此,我使用的通用模板看起来像这样(注意:这是用于不需要进度报告的情况).
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. } }} 总结 以上是内存溢出为你收集整理的android-混淆将代码放入AsyncTask全部内容,希望文章能够帮你解决android-混淆将代码放入AsyncTask所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)