WEB开发网
开发学院手机开发Android 开发 Android线程间通信的Message机制 阅读

Android线程间通信的Message机制

 2010-06-01 15:44:00 来源:WEB开发网   
核心提示:124. String msgObj = "message from mainThread";125. Message mainThreadMsg = mOtherThreadHandler.obtainMessage(1, 1, 1, msgObj);126. mOtherThreadHandle

124. String msgObj = "message from mainThread";

125. Message mainThreadMsg = mOtherThreadHandler.obtainMessage(1, 1, 1, msgObj);

126. mOtherThreadHandler.sendMessage(mainThreadMsg);

127. }

128. break;

129. case 106:

130. finish();

131. break;

132. }

133. }

134. class EventHandler extends Handler

135. {

136. public EventHandler(Looper looper) {

137. super(looper);

138. }

139. public EventHandler() {

140. super();

141. }

142. public void handleMessage(Message msg) {

143. //可以根据msg.what执行不同的处理,这里没有这么做

144. switch(msg.what){

145. case 1:

146. tv.setText((String)msg.obj);

147. break;

148. case 2:

149. tv.setText((String)msg.obj);

150. noLooerThread.stop();

151. break;

152. case 3:

153. //不能在非主线程的线程里面更新UI,所以这里通过Log打印收到的消息

154. Log.e(sTag, (String)msg.obj);

155. ownLooperThread.stop();

156. break;

157. default:

158. //不能在非主线程的线程里面更新UI,所以这里通过Log打印收到的消息

159. Log.e(sTag, (String)msg.obj);

160. break;

161. }

162. }

163. }

164. //NoLooperThread

165. class NoLooperThread extends Thread{

166. private EventHandler mNoLooperThreadHandler;

167. public void run() {

168. Looper myLooper, mainLooper;

169. myLooper = Looper.myLooper();

170. mainLooper = Looper.getMainLooper(); //这是一个static函数

171. String obj;

172. if(myLooper == null){

173. mNoLooperThreadHandler = new EventHandler(mainLooper);

174. obj = "NoLooperThread has no looper and handleMessage function

上一页  4 5 6 7 8 9 10 11 12 13 14  下一页

Tags:Android 线程 通信

编辑录入:coldstar [复制链接] [打 印]
赞助商链接