我想从php文件中检索数据到我的新android应用程序。我试着将它作为后台进程,因为我想在没有UI线程的情况下使用它。我不能从这段代码中删除UI线程,有谁能帮我删除这段代码中的UI线程,是不是?
我试过了,但是有很多红色的下划线。实际上,我尝试每隔5秒使用AlarmManager从主机获取数据
我的AlarmDemo类
public class AlarmDemo extends Activity {
Toast mToast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm_demo);
// repeated alerm
Intent intent = new Intent(AlarmDemo.this, RepeatingAlarm.class);
PendingIntent sender = PendingIntent.getBroadcast(AlarmDemo.this, 0,
intent, 0);
// We want the alarm to go off 5 seconds from now.
long firstTime = SystemClock.elapsedRealtime();
firstTime += 5 * 1000;
// Schedule the alarm!
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,
5 * 1000, sender);
// Tell the user about what we did.
if (mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(AlarmDemo.this, "Rescheduled",
Toast.LENGTH_LONG);
mToast.show();
// end repeatdalarm
}
}我的RepeatingAlarm类
public class RepeatingAlarm extends BroadcastReceiver {
Context context;
Button b;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
private AutoCompleteTextView autoComplete;
private MultiAutoCompleteTextView multiAutoComplete;
private ArrayAdapter<String> adapter;
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "OK", Toast.LENGTH_SHORT).show();
dialog = ProgressDialog.show(RepeatingAlarm.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://androidexample.com/media/webservice/getPage.php");
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
String text = response;
tv.setText("Response from PHP : " + text);
dialog.dismiss();
}
});
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
}请帮帮我,我是android新手
发布于 2016-03-13 12:56:00
使用AsyncTask:
使用AsyncTask类(reference)执行后台操作。
为什么使用AsyncTask:
它使得管理这类工作变得非常容易,因为它允许你在后台线程(也称为工作线程)中执行密集的(即长的,消耗大量资源的)操作,还允许你从UI线程(也称为主线程)操作你的UI。
如果你在UI线程上执行密集的操作,你的应用程序会挂起,你会得到“应用程序没有响应”(称为ANR)问题。如果你试图从工作线程/后台线程操作UI,你会得到一个异常。
使用AsyncTask的:
它是这样工作的:
我们将这种长时间的密集操作称为异步任务。在AsyncTask模型中,异步任务分4个步骤执行-- See them here.
阅读以下伪代码中的注释。在这段代码之后,在下一段代码中,我将向您展示如何执行AsyncTask并将参数传递给它(您可以在这段代码中看到)。
/*
* PERFORM A LONG, INTENSIVE TASK USING AsyncTask
*
* Notice the parameters of the class AsyncTask extended by AlarmClockTask.
* First represents what is passed by Android System to doInBackground() method when system calls it. This is originally passed by you when you execute the AlarmClockTask (see next snippet below to see how to do that), and then the system takes it and passes it to doInBackground()
* Second represents what is passed to onProgressUpdate() by the system. (Also originally passed by you when you call a method `publishProgress()` from doInBackground(). onProgressUpdate() is called by system only when you call publishProgress())
* Third represents what you return from doInBackground(); Then the system passes it to onPostExecute() as a parameter.
*/
public class AlarmClockTask extends AsyncTask<String, Integer, Boolean> {
@Override
protected void onPreExecute() {
/*
*
* FIRST STEP: (Optional)
*
* This method runs on the UI thread.
*
* You only set-up your task inside it, that is do what you need to do before running your long operation.
*
* In your case, the long operation is perhaps loading data from the `php` file. SO HERE you might want to show
* the progress dailog.
*/
}
@Override
protected Boolean doInBackground(String... params) {
/*
*
* SECOND STEP: (Mandatory)
*
* This method runs on the background thread (also called Worker thread).
*
* So perform your long, intensive operation here.
*
* So here you read your PHP file.
*
* Return the result of this step.
* The Android system will pass the returned result to the next onPostExecute().
*/
return null;
}
@Override
protected void onProgressUpdate(Integer... string) {
/*
* Run while the background operation is running (Optional)
*
* Runs on UI Thread
*
* Used to display any form of progress in the user interface while the background computation is still
* executing.
*
* For example, you can use it to animate a progress bar (for displaying progress of the background operation).
*/
}
protected void onPostExecute (String result) {
/*
* FOURTH STEP. Run when background operation is finished. (Optional)
*
* Runs on UI thread.
*
* The result of the background computation (what is returned by doInBackground())
* is passed to this step as a parameter.
*
*/
}
}下面是执行AsyncTask的方法
new AlarmClockTask().execute(new String[] {"alpha", "beta", "gamma"});Android系统会将您传递给execute()__的字符串数组作为doInBackground()__的varargs参数传递给doInBackground()方法。
https://stackoverflow.com/questions/35966505
复制相似问题