- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有这个代码来接收聊天消息。但是当我试图将它放在 AsyncTask
中时,我感到很困惑。当我将 read.readline()
放入 postexecute
时,我收到警告 read cannot be resolved
。
我想让这段代码在后台工作,以检查是否有任何消息。我想问一下,要使代码始终在后台运行,是使用 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();
}
}
最佳答案
您收到错误消息 read cannot be resolved
因为 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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17161188/
我真的很困惑。我已经尝试使用带有 tomcat 的 Jax-rs 并使用所有注释,我能够使用 url 调用我的服务。因此,如果没有 Jax-rs,我可以简单地拥有一个 servlet 并调用我的服务。
是否有任何工具/商业混淆器可以混淆 WPF 控件中的 BAML 资源? 如果没有,就 IP 保护而言,这是一段艰难的时期,因为黑客可以通过使用 BAML 到 XAML 转换器轻松查看 BAML 资源。
嘿大家。我在尝试使用 COBOL 在 zOS 环境中解决的编码项目中遇到了一些麻烦。我需要读入一个文件并将它们放入索引表中(我知道将少于 90 条记录)。 让我感到困扰的是,我们受到项目参数的约束,以
我试图按照这个例子来理解 join() 方法: class PrintDemo { public void printCount() { try { for(int
当我编译我正在编写的代码,然后在 JD Gui 中查看时,方法显示带有如下标题: public void growSurface(Random paramRandom, int paramInt1,
我正在为重新分发准备 Android 库,它的代码必须进行混淆处理。我已经阅读了有关此主题的一些内容,并且决定使用 Android Library Project。它将作为 jar 分发(自动在/bi
两个混淆相关的问题: 1) 是否有任何工具可以将 F# 从 MSIL 目标形式反汇编回其源形式或接近它的形式?这不是通过默默无闻来实现安全性的尝试,但我想保护某些源代码免遭“盗窃”。 2) 我简要地查
谁能向我解释为什么 simulatedCase <- rbinom(100,1,0.5) simDf <- data.frame(CASE = simulatedCase) posterior_m0
我一直无法找到关于使用 AppDomains 时发生的事情的非常清楚的描述,所以希望有人能够启发我。我有一个简单的测试程序(基本上是扯掉了 MSDN example ): using System;
假设我有 2 个分支topic和 master如果我在 topic分支,然后运行 git rebase master它是 rebase master 还是 rebase 主题分支? 做 git r
我有一个类(class): public class LockTest { public void LockThis() { lock (this)
我正在尝试最小化/混淆我的 Angular 代码,但遇到了问题。我在这里阅读“缩小说明”http://docs.angularjs.org/tutorial/step_05但我定义我的 Control
我遇到了一些困惑的操作。 var a = 0.1; var b = 0.2; var c = 0.3; console.log(a); // 0.1 console.log(b); // 0.2 co
感谢您查看我的帖子 - 我正在尝试弄清楚如何在单击链接时关闭此下拉菜单,但我的 JavaScript 技能非常缺乏,而且代码似乎很困惑。这是 HTML:
混淆、哈希和加密之间有什么区别? 这是我的理解: 哈希是一种单向算法;无法逆转 混淆与加密类似,但不需要任何“ secret ”即可理解(ROT13 就是一个例子) 加密是可逆的,但需要“ secre
我有以下代码 my $content = $response->content; $content =~ /username=([\s\S]+?)&/; my $username = $1; prin
我在 .NET 中发现了一些与我预期的有点不同的东西。我粘贴的代码没有意义,但它是我拥有的一个复杂得多的函数的浓缩版。我实际上是在获取匿名类型信息作为参数(尚未创建匿名类型的实例),我需要创建该类型的
我正在努力解决 JavaFX 应用程序的混淆问题。使用此项目作为基础: https://github.com/openjfx/samples/tree/master/IDE/IntelliJ/Non-
是否可以制作一个与此类似的 CSV 阅读器 while((line = reader.readLine()) != null){ String[] values = line.
公共(public)类测试2 { 公共(public)静态无效主(字符串[]参数){ System.out.println("3 + 6"); System.out.println(3
我是一名优秀的程序员,十分优秀!