Android 开发中的线程

来源:互联网 发布:快乐大本营直播软件 编辑:程序博客网 时间:2024/06/05 17:24
大多数的View都在是主线程中被创建出来的,所以修改View的相关属性一般都在主线程中进行。主线程一般用于接受用户的输入,以及将运算的结果反馈给用户。所以说对于一些可能会产生阻塞的操作,必须放置在Worker Thread.
//activity_main
<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=".MainActivity" >

   <ProgressBar 
       android:id="@+id/progressBarId"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       style="?android:attr/progressBarStyleHorizontal"
       />
    <Button 
         android:id="@+id/buttonId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/progressBarId"
        android:text="button" 
        />
</RelativeLayout>


//MainActivity.java
package com.example.thread;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {
private Button button;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar= (ProgressBar)findViewById(R.id.progressBarId);
button = (Button)findViewById(R.id.buttonId);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.i("Myhhread",Thread.currentThread().getName());
Thread thread = new Mythread();
thread.start();
}
});
}
class Mythread extends Thread{

@Override
public void run() {
for (int i = 0; i <=100; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
progressBar.setProgress(progressBar.getProgress()+1);Log.i("Myhhread",Thread.currentThread().getName());
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}
0 0