android多线程有多种实现方式,这里记录两种自己平时常用的方式Thread ,AsyncTask和Timer等,同时记录子线程与主线程之间的交互方式等,简单整理了代码结构
AsyncTask: 创建GenericTask类继承AsyncTask用来打包异步任务类
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
/**
* 异步任务类
* @author 爱吃鱼的cat
* @date 2013-12-23 上午10:42:55
*/
public abstract class GenericTask extends AsyncTask<Object, Object, Result>
{
private Context mContext;
private Dialog mDialog;
private boolean mIsShow;
private boolean mIsUserCancel = true;
/**
* 构造方法
* @param context 上下文环境
* @param dialog 对话框
* @param isShow 是否需要显示进度条对话框
*/
public GenericTask(Context context, Dialog dialog, boolean isShow)
{
super();
this.mContext = context;
this.mDialog = dialog;
this.mIsShow = isShow;
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
if (mIsShow)
{
// 显示等待对话框
if (mDialog == null)
{
mDialog = new Dialog(mContext);
mDialog.setContentView(R.layout.common_progressbar);
mDialog.setCanceledOnTouchOutside(false);
mDialog.setOnCancelListener(new OnCancelListener()
{
@Override
public void onCancel(DialogInterface dialog)
{
if (getStatus() == Status.RUNNING)
{
GenericTask.this.cancel(true);
}
if (mIsUserCancel)
{
doUserCancel();
}
}
});
}
mDialog.show();
}
}
/**
* 用户取消
* @author 爱吃鱼的cat
* @date 2014-6-3 上午11:10:31
*/
protected void doUserCancel()
{
}
@Override
protected abstract Result doInBackground(Object... params);
@Override
protected void onPostExecute(Result result)
{
super.onPostExecute(result);
mIsUserCancel = false;
cancleDialog();
switch (result.getFlag())
{
case Result.OK:
doSuccess(result.getExtra());
break;
case Result.FAIL:
doFail(result.getExtra());
break;
case Result.ERROR:
doError(result.getExtra());
break;
}
}
/**
* 关闭等待对话框
*
* @author 爱吃鱼的cat
* @date 2014-1-5 下午2:49:48
*/
public void cancleDialog()
{
if (mDialog != null && mDialog.isShowing())
{
mDialog.cancel();
}
}
@Override
protected void onCancelled()
{
cancleDialog();
super.onCancelled();
}
/**
* 错误处理
* @param extra
* @author 爱吃鱼的cat
* @date 2013-12-25 上午9:51:43
*/
protected void doError(Object extra)
{
}
/**
* 失败处理
* @param extra
* @author 爱吃鱼的cat
* @date 2013-12-25 上午9:51:41
*/
protected abstract void doFail(Object extra);
/**
* 成功后的处理
* @param extra
* @author 爱吃鱼的cat
* @date 2013-12-25 上午9:49:31
*/
protected abstract void doSuccess(Object extra);
}
Result 是自己创建的工具类用来传递执行信息
/**
* 任务执行结果
*
* @author 爱吃鱼的cat
* @date 2013-12-23 上午10:55:17
*/
public class Result
{
// 成功
public static final int OK = 0;
// 失败
public static final int FAIL = 1;
// 异常错误
public static final int ERROR = 2;
// 返回的数据
private Object mExtra;
// 标志位
private int mFlag;
// 返回码
private int mCode;
/**
*
*/
public Result()
{
super();
}
/**
* 构造方法
* @param flag 成功标志
* @param code 返回码
* @param extra 附加数据
*/
public Result(int flag, int code, Object extra)
{
super();
this.mFlag = flag;
this.mCode = code;
this.mExtra = extra;
}
public Object getExtra()
{
return mExtra;
}
public void setExtra(Object extra)
{
this.mExtra = extra;
}
public int getFlag()
{
return mFlag;
}
public void setFlag(int flag)
{
this.mFlag = flag;
}
public int getCode()
{
return mCode;
}
public void setCode(int code)
{
this.mCode = code;
}
}
没有指定对话框的情况下默认使用进度条对话框 mDialog.setContentView(R.layout.common_progressbar);
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
调用子线程获取屏幕分辨率的例子
@SuppressLint("ValidFragment")
public static class PlaceholderFragment extends Fragment
{
private GetScreenResolutionTask mGetResolutionTask;
private TextView mTextView;
private Button mbtnGet;
private MainActivity context;
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)
{
if (mGetResolutionTask != null && mGetResolutionTask.getStatus() == AsyncTask.Status.RUNNING)
{
return;
}
mGetResolutionTask = new GetScreenResolutionTask(context, null, true);
mGetResolutionTask.execute();
}
});
return rootView;
}
class GetScreenResolutionTask extends GenericTask
{
public GetScreenResolutionTask(Context context, Dialog dialog, boolean isShow)
{
super(context, dialog, isShow);
}
@Override
protected Result doInBackground(Object... params)
{
DisplayMetrics dm = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(dm);
String strOpt = "手机屏幕分辨率为:" + dm.widthPixels + " × " + dm.heightPixels;
return new Result(Result.OK, 0, strOpt);
}
@Override
protected void doFail(Object extra)
{
Toast.makeText(context, "获取手机屏幕分辨率失败。",Toast.LENGTH_SHORT);
}
@Override
protected void doSuccess(Object extra)
{
mTextView.setText((String)extra);
}
}
}