linux安卓主线程同步,Android解决:使用多线程和Handler同步更新UI
如果運行時,可以看到滾動條由條慢慢變短,則說明程序成功了。截圖如下,建議選擇大點的文件做測試。
? ?
main.xml
xmlns:Android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" android:id="@+id/scrollView1" android:layout_width="fill_parent">
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
FileRead.java
public class FileRead {
boolean readend=false;
List al=null;
public ?class ReadNodesThread extends Thread{//讀取線程
public void run()
{
al=new ArrayList(100);
al.clear();
readend=false;
int i=0;
try {
RandomAccessFile raf=new RandomAccessFile("/sdcard/test.txt","r");
//try {
while(raf.getFilePointer()
{
al.add(raf.readLine());
//sleep(100);//如果測試文件太小,這里休眠是為了測試,
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
readend=true;
}
};
}
MultiThreadActivity.java
public class MultiThreadActivity extends Activity {
FileRead fr=null;
Handler mHandler=null;
int curi=0;
Runnable updateui=null;
String[] tmp=null;
String s="";
TextView tv=null;
class ReadListener extends Thread{//監聽線程,當數據更新數目大于10條時,更新UI
public void run()
{
int i=0,newi=0;
while(!fr.readend)
{
newi=fr.al.size();
if((newi-i)>10)//新增數據大于10條,更新UI
{
i=newi;
tmp=(String[])fr.al.toArray(new String[fr.al.size()]);
mHandler.post(updateui);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//數據讀完了
tmp=(String[])fr.al.toArray(new String[fr.al.size()]);
mHandler.post(updateui);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv=(TextView)findViewById(R.id.tv);
fr=new FileRead();
ReadNodesThread readThread=fr.new ReadNodesThread();
updateui=new Runnable()//更新UI的線程
{
@Override
public void run() {
// TODO Auto-generated method stub
int i=0;
for(i=curi;i
{
s+=tmp[i]+"\n";
}
tv.setText(s);
curi=i;
}};
readThread.start();
ReadListener updateThread=new ReadListener();
mHandler=new Handler();
updateThread.start();
}
}
總結
以上是生活随笔為你收集整理的linux安卓主线程同步,Android解决:使用多线程和Handler同步更新UI的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux终端登录软件,小白入门之四:使
- 下一篇: linux同步硬件和系统时钟,liunx