Android 将代码放入异步任务中很困惑
我有这个代码来接收聊天信息。但当我试图将它放在Android 将代码放入异步任务中很困惑,android,android-asynctask,Android,Android Asynctask,我有这个代码来接收聊天信息。但当我试图将它放在AsyncTask中时,我感到困惑。当我将read.readline()放入post execute时,我有一个警告read无法解析 我想让这段代码在后台工作,以检查是否有任何消息传入。我想问,为了让代码始终在后台运行,是使用AsyncTask还是有其他方法 任何人请帮助我,我不知道如何使它。多谢各位 接收消息部分 HttpURLConnection connection; URL url = null; try{
AsyncTask
中时,我感到困惑。当我将read.readline()
放入post execute
时,我有一个警告read无法解析
我想让这段代码在后台工作,以检查是否有任何消息传入。我想问,为了让代码始终在后台运行,是使用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();
}
}
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();
}
}
公共课堂聊天室扩展活动{
公共Koneksi链接URL;
字符串服务器地址;
私有编辑文本消息文本;
私有文本视图meLabel;
私有文本视图标签;
私有视图组消息容器;
私有滚动视图滚动容器;
/*私有处理程序=新处理程序()*/
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.chatpage);
messagesContainer=(视图组)findViewById(R.id.messagesContainer);
scrollContainer=(ScrollView)findViewById(R.id.scrollContainer);
按钮sendMessageButton=(按钮)findViewById(R.id.sendButton);
Bundle Bundle=this.getIntent().getExtras();
/*最终字符串paramnama=bundle.getString(“nama”)*/
messageText=(EditText)findViewById(R.id.messageEdit);
meLabel=(TextView)findViewById(R.id.meLabel);
friendLabel=(TextView)findViewById(R.id.friendLabel);
meLabel.setText(“我”);
最终字符串param1=bundle.getString(“keyCourseId”);
最终字符串param2=bundle.getString(“keyUserId”);
最终字符串param3=bundle.getString(“keyChatsId”);
String param4=bundle.getString(“keyMessagesId”);
sendMessageButton.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
ArrayList后参数=新的ArrayList();
添加(新的BasicNameValuePair(“messages”,messageText.getText().toString());
字符串响应=null;
试一试{
linkurl=newkoneksi(聊天室,this);
SERVER_URL=linkurl.getUrl();
SERVER_URL+=“/mobile/ChatKirimTeks.php?idu=“+param2+”&idch=“+param3;
response=CourseHttpClient.executeHttpPost(服务器URL,后参数);
String res=response.toString();
res=res.trim();
res=res.replaceAll(“\\s+”,”);
如果(相对等于(“1”)){
字符串messageString=messageText.getText().toString();
showMessage(messageString,true);
messageText.getText().clear();
}否则
{
createDialog(“Maaf”、“消息和Gagal Terkirim”);
}
}
捕获(例外e){
messageText.setText(例如toString());
}
}
});
httpurl连接;
URL=null;
试一试{
linkurl=新的Koneksi(本);
SERVER_URL=linkurl.getUrl();
SERVER_URL+=“/mobile/ChatRoom.php?idu=“+param2+”&idch=“+param3+”&idcm=“+param4;
url=新url(服务器url);
connection=(HttpURLConnection)url.openConnection();
connection.setDoOutput(真);
connection.setRequestProperty(“内容类型”、“应用程序/x-www-form-urlencoded”);
connection.setRequestMethod(“POST”);
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(服务器URL);
//ArrayList param=新的ArrayList();
//添加参数
//setEntity(新的UrlEncodedFormEntity(参数));
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpRespose.getEntity();
//阅读内容
InputStream in=httpEntity.getContent();
BufferedReader read=新的BufferedReader(新的InputStreamReader(in));
字符串msg=“tes”;
while(true)
{
试一试{
msg=read.readLine();
Log.d(“,”MSGGG:“+msg”);
//msgList.add(msg);
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 getMessage();
}
如果(msg==null)
{
打破
}
其他的
{
showMessage(msg,false);
}
}}
捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
公共类ReceivedTask扩展异步任务{
@凌驾
受保护的void onPreExecute(){
}
@凌驾
受保护的字符串doInBackground(字符串…arg0){
//TODO自动生成的方法存根
httpurl连接;
URL=null;
试一试{
linkurl=newkoneksi(聊天室,this);
SERVER_URL=linkurl.getUrl();
SERVER_URL+=“/mobile/ChatRoom.php?idu=“+param2+”&idch=“+param3+”&idcm=“+param4;
url=新url(服务器url);
connection=(HttpURLConnection)url.openConnection();
connection.setDoOutput(真);
connection.setRequestProperty(“内容类型”,
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();
}
}
@Override
protected void onPostExecute(String result) {
String msg = "tes"; // Why? You have 'result' String reference one line above.
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.
}
}
}