androidannotations的background和UiThread配合使用参考

简介

androidannotations在开发中的代码规范思考:(MVC思考)时间太紧,先贴代码:

Activity的代码:
package edu.njupt.zhb.main;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EActivity;

import android.app.Activity;

/**
 * @author Zheng Haibo
 * @web  http://www.mobctrl.net
 */
@EActivity(R.layout.main)
public class MainActivity extends Activity {

	@Bean
	MainActions mainActions;

	@AfterViews
	void afterViews() {
		doSomething();
	}

	private void doSomething() {
		mainActions.doActionsInThread(20, new UiCallback() {

			@Override
			public void onBackgroundEnd() {
				// TODO Auto-generated method stub
				// write the code
				System.out.println("the background thread end...");
			}
		});
	}
}

业务逻辑
MainActions
package edu.njupt.zhb.main;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.RootContext;
import org.androidannotations.annotations.UiThread;

import android.content.Context;
import android.widget.Toast;
/**
 * @author Zheng Haibo
 * @web  http://www.mobctrl.net
 */
@EBean
public class MainActions {

	@RootContext
	Context context;

	@Background
	void doActionsInThread(int params, UiCallback uiCallback) {
		// database,net,file,sp ...
		int result = 0;
		for (int i = 0; i < params; i++) {
			result = result + i;
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("test the thread is run in the background...");
		}
		runInUiThread(result, uiCallback);
	}

	@UiThread
	void runInUiThread(int result, UiCallback uiCallback) {
		Toast.makeText(context, result + ", just a test", Toast.LENGTH_SHORT)
				.show();
		System.out.println("you can write the ui code ...");
		uiCallback.onBackgroundEnd();
	}
}

回调接口

package edu.njupt.zhb.main;

/**
 * @author Zheng Haibo
 * @web http://www.mobctrl.net
 */
public interface UiCallback {
	public void onBackgroundEnd();
	// ...
}

我觉得按照这个思路写,代码会比较清爽。后续说原因,先回宿舍了。。。。

你可能感兴趣的:(androidannotations的background和UiThread配合使用参考)