前面已经介绍了AsyncTask,现在介绍Thread。
继承Thread捕捉run()异常避免因为线程中出现异常导致程序崩溃
/**安全线程抽象类
* Description:安全线程抽象类,此线程类已经封闭run函数,添加抽象函数runs,后者只需将业务代码放入runs中即可,可有效防止在线程中出现未捕获的异常而导致程序崩溃
* @author 爱吃鱼的cat
* @date 2013-1-18
*/
public abstract class Thread extends java.lang.Thread
{
/**
* 线程 实际执行函数,已被封闭,请实现runs方法将业务处理相关动作放在里面
*/
@Override
public final void run()
{
try
{
runs();
} catch (Exception e)
{
Log.e("Thread","-----------------线程执行出现未捕获异常------------------");
e.printStackTrace();
}
}
/**
* 线程执行函数,里面执行业务代码
*/
public abstract void runs();
}
使用Thread创建子线程与界面交互有两种方式第一种使用runOnUiThread
new Thread()
{
@Override
public void runs()
{
DisplayMetrics dm = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(dm);
String strOpt = "手机屏幕分辨率为:" + dm.widthPixels + " × " + dm.heightPixels;
runOnUiThread(new Runnable()
{
public void run()
{
mTextView.setText((String)extra);
}
});
}
}.start();
第二种方式是使用Handle,Handler来根据接收的消息,处理UI更新。Thread线程发出Handler消息,通知更新UI。
@SuppressLint("ValidFragment")
public static class PlaceholderFragment extends Fragment
{
private TextView mTextView;
private Button mbtnGet;
private MainActivity context;
Handler myHandler = new Handler()
{
public void handleMessage(Message msg)
{
switch (msg.what)
{
case 0x01:
mTextView.setText((String) msg.obj);
break;
}
super.handleMessage(msg);
}
};
public PlaceholderFragment()
{
super();
}
public PlaceholderFragment(MainActivity context)
{
this.context = context;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_main, container,false);
mbtnGet = (Button)rootView.findViewById(R.id.myButton)
mTextView = (TextView) rootView.findViewById(R.id.myTextView);
mbtnGet.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
new Thread()
{
@Override
public void runs()
{
DisplayMetrics dm = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(dm);
String strOpt = "手机屏幕分辨率为:" + dm.widthPixels + " × " +dm.heightPixels;
Message message = new Message();
message.what = 0x01;
message.obj = strOpt;
myHandler.sendMessage(message);
}
}.start();
}
});
return rootView;
}
}