我想从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的新手
答案 0 :(得分:1)
使用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()
的String数组传递给doInBackground()
方法作为doInBackground()
的varargs参数。