2016-03-13 32 views
0

我想檢索數據從PHP文件到我的新的Android應用程序。我試圖做它作爲後臺進程,因爲我想在沒有UI線程的情況下使用它。我無法從此代碼中刪除UI線程任何人都可以在此代碼中刪除UI線程嗎?檢索數據沒有UI線程

我試了一下,但有很多紅色的下劃線。 其實我嘗試在每5秒

我AlarmDemo類來獲得從使用AlarmManager主機數據

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()); 
     } 
    } 
} 

請幫助我,我在安卓

回答

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系統將爲您傳遞給​​這個字符串數組,傳遞給doInBackground()方法的doInBackground()的可變參數的參數。