標籤:檔案 rup change data void override 架構 天氣 ges
android中的幾種多線程實現方式:
1)Activity.runOnUiThread(Runnable)
2)View.post(Runnable) ;View.postDelay(Runnable , long)
3)Handler
4)AsyncTask
介紹AsyncTask寫法
用非同步任務架構多任務模型其實也不是很健壯,得建立多個AsyncTask執行個體。一個AsyncTask僅執行一次,不能重複執行,快餐類的線程,一次用完。
實現AsyncTask子類,最重要的兩個方法,一個是doInBackground(params);一個是onPostExecute(result)。在doInBackground()方法裡處理耗時事務,並把結果返回,返回的值將在onPostExecute方法作為參數,然後就可以在onPostExecute()把結果展示在ui上面了。
步驟:
①執行個體化AsyncTask:
執行個體化AsyncTask然後通過task.exec(pamas);傳進去參數,這個參數列表是動態,可以是一個也可以使多個,長度可變。
AsyncTask<params,values,reslut>,第一個參數會傳進去這個方法doInBackground(params),第二個參數是資料更新的值,第三個是處理事務返回的結果。
②onPreExecute方法:
這個方法沒有參數,也沒有傳回值,可以在這個方法裡,做一些提醒。比如show一個Dialog,或者彈個Toast告訴使用者開始下載啦。
③doInBackground(params)方法:
進入AsyncTask內部結構,首先將執行reslut doInBackground(params)方法,這個方法將處理耗時事務,exec()的參數將會傳進這個方法做參數,而傳回值將會作為onPostExecute()的參數。如果要更新進度的話,需執行publicProgress()方法。
④onProgressUpdate(values)方法:
這個方法的參數必須在doInBackground()方法裡執行publicProgress()方法,這個方法將會把參數傳遞進onProgressUpdate()方法裡,然後可以在這個方法做一些ui上的更新展示,比如進度條的值就可以通過這個values值動態改變。
⑤onPostExecute(result)方法:
這裡就是交易處理完畢的走的方法,doInBackground方法執行的結果將傳到這裡,如果這個方法返回了資料。在這個方法裡可以處理Ui,可以把處理完的資料展示在ui上。比片啊,文字啊,一切你想要的結果。
案列
1、添加android專案檔
2、添加類繼承AsyncTask,專案檔如下
用listview顯示資料
3、添加布局檔案,布局如下
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.multithreadind01.MainActivity" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignTop="@+id/textView1" android:layout_marginRight="53dp" android:text="Button" /> <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/button1" android:layout_marginTop="84dp" > </ListView> <ProgressBar android:id="@+id/progressBar1" style="?android:attr/progressBarStyleHorizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/listView1" android:layout_alignRight="@+id/button1" android:layout_below="@+id/button1" android:layout_marginTop="28dp" /></RelativeLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <TextView android:id="@+id/username" android:layout_weight="1" android:layout_width="match_parent" android:layout_height="60dp" android:textSize="45dp" /> <TextView android:id="@+id/sex" android:layout_weight="1" android:layout_width="match_parent" android:layout_height="60dp" android:textSize="45dp" /></LinearLayout>
MainActivity類代碼:綁定資料
public class MainActivity extends Activity { private String fromDb_str1 = ""; private Button btn; private TextView tv; private ListView lv; private BaseAdapter adapter; private List<User> userList = new ArrayList<User>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); for (int i = 0; i < 5; i++) { User u = new User(); u.setUsername("小明"+i); u.setSex("女"+i); userList.add(u); } tv =(TextView)findViewById(R.id.textView1); btn =(Button)findViewById(R.id.button1); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MyTask mt = new MyTask(MainActivity.this); mt.execute(userList,adapter);//裡面的參數是傳給doInBackground /* Thread t1 = new Thread(new Runnable() { @Override public void run() { fromDb_str1 = "測試"; } }); t1.start(); tv.setText(fromDb_str1); */ } }); adapter = new BaseAdapter(){ @Override public int getCount() { // TODO Auto-generated method stub return userList.size(); } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = MainActivity.this.getLayoutInflater(); View view; if (convertView==null){ view = inflater.inflate(R.layout.item, null); } else{ view = convertView; } TextView tv_username = (TextView)view.findViewById(R.id.username); TextView tv_sex = (TextView)view.findViewById(R.id.sex); tv_username.setText(userList.get(position).getUsername()); tv_sex.setText(userList.get(position).getSex()); return view; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } }; lv = (ListView)findViewById(R.id.listView1); lv.setAdapter(adapter); }}
MyTask類,應用多線程,顯示資料
package com.example.multithreadind01;import java.util.List;import android.os.AsyncTask;import android.view.View;import android.widget.BaseAdapter;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast;public class MyTask extends AsyncTask { private BaseAdapter adapter; private List<User> userList; private MainActivity activity; public MyTask(MainActivity activity){ this.activity = activity; } //1.所有耗時的代碼,寫到這裡來(資料庫、藍芽、網路服務) //2.絕對不能碰UI @Override protected Object doInBackground(Object... params) { userList = (List<User>) params[0]; adapter = (BaseAdapter) params[1]; for (int i = 0; i < userList.size(); i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } userList.get(i).setUsername("小紅"+i); userList.get(i).setSex("男"+i); publishProgress(i); } //userlist,adapter //返回給前端 return "天氣:22度"; } //準備 @Override protected void onPreExecute() { Toast.makeText(activity, "今晚不錯啊", Toast.LENGTH_SHORT).show(); } //做完後執行 @Override protected void onPostExecute(Object result) { String r = result.toString(); TextView tv = (TextView)activity.findViewById(R.id.textView1); tv.setText("訪問完成!"+r); } //分步完成 @Override protected void onProgressUpdate(Object... values) { // TODO Auto-generated method stub //0,1,2,3,4 int bar = Integer.parseInt(values[0].toString()); bar = (bar+1)*20; ProgressBar progressBar = (ProgressBar)activity.findViewById(R.id.progressBar1); progressBar.setProgress(bar); adapter.notifyDataSetChanged(); }}
:開始介面,進行中,完成時
寫安卓項目,我們應該一步一步來,一個功能一個功能去測試,而不是寫完全部再去測試,這樣出錯誤的話,找錯誤都不知道怎麼找,應該穩打穩紮,
錯誤才好找,效率才會高。
android開發--多線程