PS: 我是个Android土鳖,学Android才不到两个月,有槽点就尽情吐吧。
--------------我是分割线--------------------------------------------------------------
我们知道WPF (WinForm)的UI操作是不能在UI主线程以外进行的。但是WPF和Winform都有比较方便的代码写法来支持这个调用。
比如
this.Dispatcher.Invoke(new Action(() =>
{
if (_userInfo.mLoginResult == false)
{
System.Windows.MessageBox.Show("登陆失败 : " + _userInfo.mStatus);
}
else
{
EnterPage();
}
}));
我现在希望我的Android程序在执行多线程代码的时候,也能这么方便的书写代码。
DispatchInvoker Dispatcher = null; TextView mTextInfo = null; public YourActivity() { Dispatcher = new DispatchInvoker(); }构造好了以后,这样使用。
public void OnPostFinish(String _ret) { mTextInfo.setText(_ret); } public void OnBtnTestClick(View view) { Thread _thread = new Thread(new Runnable() { @Override public void run() { UploadImage _upload = new UploadImage(); final String _ret = _upload.testUpload(); Dispatcher.Invoke( new IDispatcher(Dispatcher) { @Override public void OnAction() { OnPostFinish(_ret); } }); } }); _thread.start(); return ; }虽然没C#的代码优美,也凑合着看吧。总比写一堆Handler handleMessage啥的强多了。
另外,还可以把new出来的IDispatcher对象的实例做参数传到线程代码深处,作为回调函数使用。同时 OnAction有个带参数的版本OnAction(Object _arg)。方便回调的时候传个参数过来。
下面是两个支撑的类
IDispatcher.java
package com.example.stanlylee.testhttpupload; import android.os.Message; /** * Created by stanlylee on 2015/7/16. */ public class IDispatcher { private DispatchInvoker invoker = null; public void OnAction(Object _arg) { } public void OnAction() { } public Object mArg = null; public void Invoke(Object _arg) { mArg = _arg; invoker.Invoke(this); } IDispatcher(DispatchInvoker _invoker) { invoker = _invoker; } }
DispatchInvoker.java
package com.example.stanlylee.testhttpupload; import android.os.Handler; import android.os.Message; /** * Created by stanlylee on 2015/7/16. */ public class DispatchInvoker { public Handler mHandler = new Handler(); public void Invoke(IDispatcher dispatcher) { Message _msg = Message.obtain(); _msg.obj = dispatcher; mHandler.sendMessage(_msg); } public DispatchInvoker() { mHandler = new Handler() { public void handleMessage(Message msg) { onMessage(msg); super.handleMessage(msg); } }; } protected void onMessage(Message msg) { IDispatcher _disp = (IDispatcher) msg.obj; if (_disp.mArg == null) _disp.OnAction(); else _disp.OnAction(_disp.mArg); } }