1.基于监听的事件处理
主要做法就是为Android界面组件绑定特定的事件监听器
package com.example.monitorevent;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText et1,et2,et3,et4;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = (EditText)findViewById(R.id.et1);
et2 = (EditText)findViewById(R.id.et2);
et3 = (EditText)findViewById(R.id.et3);
et4 = (EditText)findViewById(R.id.et4);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//获取系统的Configuration
Configuration cfgConfiguration = getResources().getConfiguration();
String screen = cfgConfiguration.orientation ==
Configuration.ORIENTATION_LANDSCAPE ? "横向屏幕":"竖向屏幕";
String mncCodeString = cfgConfiguration.mnc+"";
String naviName = cfgConfiguration.orientation ==
Configuration.NAVIGATION_NONAV
? "没有方向控制":
cfgConfiguration.orientation == Configuration.NAVIGATION_WHEEL
? "滚轮控制方向":
cfgConfiguration.orientation == Configuration.NAVIGATION_DPAD
?"方向控制方向":"轨迹球控制方向";
String touchNameString = cfgConfiguration.touchscreen ==
Configuration.TOUCHSCREEN_NOTOUCH
? "无触摸屏":"支持触摸屏";
et1.setText(screen);
et2.setText(mncCodeString);
et3.setText(naviName);
et4.setText(touchNameString);
}
});
}
}
2.Handler消息传递机制
(1)Handler类的主要作用是:
在新启动的线程中发送消息
在主线程中获取、处理消息
(2)在线程中使用Handler的步骤如下:
调用Looper的prepare()方法为当前线程创建Looper对象
有了Looper之后,创建Handler子类的实例,重写handleMessage()方法,该方法负责处理来自于其他线程的消息
调用Looper的loop()方法启动Looper。
示例如下:
package com.example.primenumber;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
static final String UPPER_NUM = "upper";
EditText editText;
Button button;
CalThread calThread;
String divisorString;
TextView tView;
public class CalThread extends Thread{
public Handler handler;
public void run(){
Looper.prepare();
handler = new Handler(){
@Override
public void handleMessage(Message message){
if(message.what == 0x123){
int upper = message.getData().getInt(UPPER_NUM);
List<Integer> numsIntegers = new ArrayList<Integer>();
for(int i=1;i<=upper;i++){
if(upper % i == 0){
numsIntegers.add(i);
}
}
divisorString = numsIntegers.toString();
}
}
};
Looper.loop();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.et);
calThread = new CalThread();
calThread.start();
tView = (TextView)findViewById(R.id.tv);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Message msg = new Message();
msg.what = 0x123;
Bundle bundle = new Bundle();
bundle.putInt(UPPER_NUM,Integer.parseInt(editText.getText().toString()));
msg.setData(bundle);
calThread.handler.sendMessage(msg);
tView.setText(divisorString);
}
});
}
}
3.异步任务(AsyncTask)
AsyncTask,它使创建需要与用户界面交互的长时间运行的任务变得更简单。相对来说AsyncTask更轻量级一些,适用于简单的异步处理,不需要借助线程和Handler即可实现。
使用AsyncTask只要如下三步即可
(1)创建AsyncTask的子类,并为三个泛型参数指定类型。如果某个参数不需要指定类型,可将它指定为Void。
(2)根据需要,实现AsyncTask的如下方法。
*doInBackground(Params...):重写该方法就是后台线程将要完成的任务。该方法可以调用publishProgress(Progress... values)方法更新任务的执行进度。
*onProgressUpdate(Progress... values):在doInBackground()方法中调用publishProgress()方法更新任务的执行进度后,将会触发该方法。
*onPreExecute():该方法将在执行后台耗时操作前被调用。通常该方法用于完成一些初始化的准备工作,比如在界面上显示进度条等。
*onPostExecute(Result result):当doInBackground()完成后,系统会自动调用onPostExecute()方法,并将doInBackground()方法的返回值传给该方法。
(3)调用AsyncTask子类的实例的execute(Paras... paras)开始执行耗时任务。
使用AsyncTask时必须遵守如下规则。
(1)必须在UI线程中创建AsyncTak的实例。
(2)必须在UI线程中调用AsyncTask的execute()方法。
(3)AsyncTask的onPreExecute()、onPostExecute(Result result)、doInBackground(Params... params)、onProgressUpdate(Progress... values)方法,不应该由程序员代码调用,而是由Android系统负责调用。
(4)每个AsyncTask只能被执行一次,多次调用将会引发异常。
package com.example.asynctasktest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.R.integer;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView show;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = (TextView)findViewById(R.id.tv);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
DownTask task = new DownTask(MainActivity.this);
try {
task.execute(new URL("http://www.baidu.com"));
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
}
public class DownTask extends AsyncTask<URL, Integer, String>{
ProgressDialog pDialog;
int hasRead = 0;
Context context;
public DownTask(Context ctx){
context = ctx;
}
@Override
protected String doInBackground(URL... params) {
StringBuilder sbBuilder = new StringBuilder();
try {
URLConnection connection = params[0].openConnection();
BufferedReader bReader = new BufferedReader(
new InputStreamReader(connection.getInputStream()
,"utf-8"));
String line = null;
while((line = bReader.readLine()) != null){
sbBuilder.append(line+"\n");
hasRead++;
publishProgress(hasRead);
}
return sbBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result){
show.setText(result);
pDialog.dismiss();
}
@Override
protected void onPreExecute(){
pDialog = new ProgressDialog(context);
//设置对话框标题
pDialog.setTitle("任务正在执行中");
//设置对话框显示内容
pDialog.setMessage("任务正在执行中,敬请等待...");
//设置对话框不能用“取消”按钮关闭
pDialog.setCancelable(false);
//设置该进度条的最大进度值
pDialog.setMax(202);
//设置对话框的进度条风格
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//设置对话框的进度条是否显示进度
pDialog.setIndeterminate(false);
pDialog.show();
}
@Override
protected void onProgressUpdate(Integer...values){
show.setText("已经读取了【“+values[0]+”】行!");
pDialog.setProgress(values[0]);
}
}
}