AD

Message Android in the flexible application of the mechanism (b)

1.5. Code example


The following examples we will show the corresponding android features, interface in the following:

Message Android in the flexible application of the mechanism (b)


Code is as follows, in a later section code Description:

package com.android.messageexample; 
import android.app.Activity; 
import android.content.Context; 
import android.graphics.Color; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Looper; 
import android.os.Message; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.LinearLayout; 
import android.widget.TextView; 
public class MessageExample extends Activity implements OnClickListener { 
private final int WC = LinearLayout.LayoutParams.WRAP_CONTENT; 
private final int FP = LinearLayout.LayoutParams.FILL_PARENT; 
public TextView tv; 
private EventHandler mHandler; 
private Handler mOtherThreadHandler=null; 
private Button btn, btn2, btn3, btn4, btn5, btn6; 
private NoLooperThread noLooerThread = null; 
private OwnLooperThread ownLooperThread = null; 
private ReceiveMessageThread receiveMessageThread =null; 
private Context context = null; 
private final String sTag = "MessageExample"; 
private boolean postRunnable = false; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
       super.onCreate(savedInstanceState); 
       context = this.getApplicationContext(); 
       LinearLayout layout = new LinearLayout(this); 
       layout.setOrientation(LinearLayout.VERTICAL); 
       btn = new Button(this); 
       btn.setId(101); 
       btn.setText("message from main thread self"); 
       btn.setOnClickListener(this); 
       LinearLayout.LayoutParams param = 
         new LinearLayout.LayoutParams(250,50); 
       param.topMargin = 10; 
       layout.addView(btn, param); 
       btn2 = new Button(this); 
       btn2.setId(102); 
       btn2.setText("message from other thread to main thread"); 
       btn2.setOnClickListener(this); 
       layout.addView(btn2, param); 
       btn3 = new Button(this); 
       btn3.setId(103); 
       btn3.setText("message to other thread from itself"); 
       btn3.setOnClickListener(this); 
       layout.addView(btn3, param); 
       btn4 = new Button(this); 
       btn4.setId(104); 
       btn4.setText("message with Runnable as callback from other thread to main thread"); 
       btn4.setOnClickListener(this); 
       layout.addView(btn4, param); 
       btn5 = new Button(this); 
       btn5.setId(105); 
       btn5.setText("main thread's message to other thread"); 
       btn5.setOnClickListener(this); 
       layout.addView(btn5, param); 
       btn6 = new Button(this); 
       btn6.setId(106); 
       btn6.setText("exit"); 
       btn6.setOnClickListener(this); 
       layout.addView(btn6, param); 
       tv = new TextView(this); 
       tv.setTextColor(Color.WHITE); 
       tv.setText(""); 
       LinearLayout.LayoutParams param2 = 
          new LinearLayout.LayoutParams(FP, WC); 
       param2.topMargin = 10; 
       layout.addView(tv, param2); 
       setContentView(layout);     
       
       // The main thread to send a message to the other thread, here create the  other thread 
   receiveMessageThread = new ReceiveMessageThread(); 
   receiveMessageThread.start(); 
} 

//implement the OnClickListener interface 
@Override 
public void onClick(View v) { 
   switch(v.getId()){ 
   case 101: 
// The main thread to send a message to yourself   
Looper looper; 
looper = Looper.myLooper();   //get the Main looper related with the main thread 
// If you don't give any parameter will use the current thread to the corresponding  Looper( This is the  Main Looper) As a member of the Handler inside  mLooper Assignment   
mHandler = new EventHandler(looper); 
//mHandler = new EventHandler(); 
//  Clears the entire MessageQueue message in   
mHandler.removeMessages(0); 
String obj = "This main thread's message and received by itself!"; 
// Get Message object   
Message m = mHandler.obtainMessage(1, 1, 1, obj); 
//  The Message object into the  main thread MessageQueue inside   
mHandler.sendMessage(m); 
break; 
   case 102: 
//other Thread to send a message to the main thread   
postRunnable = false; 
noLooerThread = new NoLooperThread(); 
noLooerThread.start(); 
break; 
   case 103:   
//other thread Gets the message sent by its own   
tv.setText("please look at the error level log for other thread received message"); 
ownLooperThread = new OwnLooperThread(); 
ownLooperThread.start(); 
break; 
   case 104:     
//other thread Send by Post Runnable message to the main thread   
postRunnable = true; 
noLooerThread = new NoLooperThread(); 
noLooerThread.start(); 
break; 
   case 105:     
// Send a message to the main thread  other thread 
if(null!=mOtherThreadHandler){ 
tv.setText("please look at the error level log for other thread received message from main thread"); 
String msgObj = "message from mainThread"; 
Message mainThreadMsg = mOtherThreadHandler.obtainMessage(1, 1, 1, msgObj); 
mOtherThreadHandler.sendMessage(mainThreadMsg); 
} 
break; 
   case 106: 
finish(); 
break; 
   } 
} 
class EventHandler extends Handler 
{ 
   public EventHandler(Looper looper) { 
super(looper); 
   } 
   public EventHandler() { 
super(); 
   } 
   public void handleMessage(Message msg) { 
// You can perform different treatment msg.what  , This is not to do so   
switch(msg.what){ 
case 1: 
tv.setText((String)msg.obj); 
break; 
case 2: 
tv.setText((String)msg.obj); 
noLooerThread.stop(); 
break; 
case 3: 
// Cannot be a non-primary thread which updates the UI, so here's  Log Print the received messages   
Log.e(sTag, (String)msg.obj); 
ownLooperThread.stop(); 
break; 
default: 
// Cannot be a non-primary thread which updates the UI, so here's  Log Print the received messages   
Log.e(sTag, (String)msg.obj); 
break; 
} 
   } 
} 
//NoLooperThread 
class NoLooperThread extends Thread{ 
   private EventHandler mNoLooperThreadHandler; 
   public void run() { 
Looper myLooper, mainLooper; 
myLooper = Looper.myLooper(); 
mainLooper = Looper.getMainLooper(); // This is a static function   
String obj; 
if(myLooper == null){ 
mNoLooperThreadHandler = new EventHandler(mainLooper); 
obj = "NoLooperThread has no looper and handleMessage function executed in main thread!"; 
} 
else { 
mNoLooperThreadHandler = new EventHandler(myLooper); 
obj = "This is from NoLooperThread self and handleMessage function executed in NoLooperThread!"; 
} 
mNoLooperThreadHandler.removeMessages(0); 
if(false == postRunnable){ 
//send message to main thread 
Message m = mNoLooperThreadHandler.obtainMessage(2, 1, 1, obj); 
mNoLooperThreadHandler.sendMessage(m); 
Log.e(sTag, "NoLooperThread id:" + this.getId()); 
}else{ 
// Following the implementation of the new  Runnable Interface objects run function is  Main Thread In the execution, not in  NoLooperThread In execution   
// Note the Runnable is an interface  , It's run function is executed will not be creating a new thread   
// You can run it on a breakpoint and then in the  eclipse Debugging at which thread for execution   
mNoLooperThreadHandler.post(new Runnable(){   
    @Override   
    public void run() {   
   tv.setText("update UI through handler post runnalbe mechanism!"); 
   noLooerThread.stop(); 
    }   
});   
} 
   } 
} 

//OwnLooperThread has his own message queue by execute Looper.prepare(); 
class OwnLooperThread extends Thread{ 
   private EventHandler mOwnLooperThreadHandler; 
   public void run() { 
Looper.prepare(); 
Looper myLooper, mainLooper; 
myLooper = Looper.myLooper(); 
mainLooper = Looper.getMainLooper(); // This is a static function   
String obj; 
if(myLooper == null){ 
mOwnLooperThreadHandler = new EventHandler(mainLooper); 
obj = "OwnLooperThread has no looper and handleMessage function executed in main thread!"; 
} 
else { 
mOwnLooperThreadHandler = new EventHandler(myLooper); 
obj = "This is from OwnLooperThread self and handleMessage function executed in NoLooperThread!"; 
} 
mOwnLooperThreadHandler.removeMessages(0); 
// Send yourself a message   
Message m = mOwnLooperThreadHandler.obtainMessage(3, 1, 1, obj); 
mOwnLooperThreadHandler.sendMessage(m); 
Looper.loop(); 
   } 
} 

//ReceiveMessageThread has his own message queue by execute Looper.prepare(); 
class ReceiveMessageThread extends Thread{ 
   public void run() { 
Looper.prepare(); 
mOtherThreadHandler = new Handler(){ 
public void handleMessage(Message msg) { 
    Log.e(sTag, (String)msg.obj); 
} 
}; 
Looper.loop(); 
   } 
} 

} 


Use Looper.myLooper static method to obtain the current thread Looper object.

Use mHandler = new EevntHandler (Looper.myLooper ()); can be established to deal with the current thread of the Handler object; which, EevntHandler is a subclass of Handler.

Use mHandler = new EevntHandler (Looper.getMainLooper ()); can be established to deal with main thread of the Handler object; which, EevntHandler is a subclass of Handler.
1.5.1. The main thread to send a message to their sample

The main thread to send a message:

In the onClick of the case 101 to create a succession of self-Handler of EventHandler object, then get a message, then call the sendMessage EventHandler object to send a message to the main thread of MessageQueue. The main thread created by the system, the system will give it a Looper object and MessageQueue, so it can receive messages. Here as long as the object according to initialize the main thread Looper EventHandler object, you can send messages through the EventHandler object to the main thread's message queue.

The main thread processing messages:

Here is the function through the EventHandler's handleMessage deal, which received Message object what is the value of a message sent to it, then the message which comes on the string displayed in the TextView.
1.5.2. The other thread to the main thread to send a message example

Send a message other threads (here is say to use as a callback message Runnable):

First postRunnable set false, that is not conducted through the Runnable news and related operations. Then start the thread noLooerThread, then the main thread Looper EventHandler object as an argument to establish the object mNoLooperThreadHandler, then get a Message and assign it to a string, a member of obj, and then mNoLooperThreadHandler the message to the MessageQueue in the main thread.

The main thread processing messages:

Here is the function through the EventHandler's handleMessage deal, which received Message object what is the value of the second message sent to it above, then the string attached to the message which is displayed on the TextView.
1.5.3. Other threads send messages to their sample

Other threads to send a message:

After other non-mainline Cheng Jianli not own Looper object, so it does not MessageQueue, need to send a message of non-main thread in order to receive messages need to create MessageQueue. The following explains how to build their own object MessageQueue and Looper. The run function from OwnLooperThread see a Looper.prepare () call, this is used to create non-main thread of the MessageQueue and Looper object.

So here is to establish the process to send a message thread mOwnLooperThread, then the thread set up their own Looper and MessageQueue object, and then set up Looper above object the establishment of the corresponding EventHandler object mOwnLooperThreadHandler, then mOwnLooperThreadHandler establishment message and send to your MessageQueue inside.

Other threads handle incoming messages:

Thread to receive messages need to run a function Looper.loop (), then loop function will remove the message from the MessageQueue Handler to the corresponding object mOwnLooperThreadHandler treatment of handleMessage function in mOwnLooperThreadHandler Message object what would the value III message (the message sent above) to print out the Log, you can Logcat tool to view the log.
1.5.4. Runnable other threads to the main thread for the message parameter to send a message example

Send a message other threads (here is that the use Runnable as a callback message):

First postRunnable set true, said the way through Runnable news and related operations. Then start the thread noLooerThread, then the main thread Looper EventHandler object as an argument to establish the object mNoLooperThreadHandler, then get a Message and assign it to a string, a member of obj, and then mNoLooperThreadHandler the message to the MessageQueue in the main thread.

The main thread processing messages:

The main thread to send the Message received after the above run directly above the Runnable object in the corresponding operation run functions. Log print run through a string function, you can Logcat tool to view the log.
1.5.5. The main thread to send messages to other threads example

The main thread to send a message:

Thread receiveMessageThread first asked to run here (in the onCreate function completed), and ready to own Looper and MessageQueue (ReceiveMessageThread in this run through the function of Looper.prepare () call to complete), then initializes the object according to the established Looper Handler object mOtherThreadHandler. Then in the onClick of the case 105 in a message from the mOtherThreadHandler (message, there is a string object) and sent to the thread in receiveMessageThread the MessageQueue.

Other threads handle incoming messages:

Thread to receive messages need to run a function Looper.loop (), then loop function will remove the message from the MessageQueue Handler to the corresponding object mOtherThreadHandler treatment of handleMessage in mOtherThreadHandler Message object will function string object Log in to print out, you can Logcat tool to view the log.
标签: boolean, public void, code description, implements, interface, widget, btn, android, new button, private button, private context, flexible application, topmargin, int fp, stag
分类: Mobile
时间: 2010-05-14

相关文章

  1. Message android in the flexible application of the mechanism

    Message android in the flexible application of the mechanism Keywords: Message-handler looper threads communic ...
  2. Message Android in the flexible application of the mechanism (1)

    Utilize Android Message communication mechanism between threads 1.1.Message Code in the frameworks \ base \ co ...
  3. Flexible mechanism in the Message Android application (1)

    Reprinted from easyandroid Forum please specify Utilize Android Message communication mechanism between thread ...
  4. Android JSON-based data exchange application

    JSON definition: A lightweight data interchange format, has a good quick read and easy to write features. The ...
  5. Android之旅[2] -Application Framework

    本文主要是Inside the Android Application Framework的随笔记录. Managed Component Lifecycle An Android APK is a collection ...
  6. android completely close the application back to capture key

    In the development of android application, often by pressing the back key (the keyCode == KeyEvent.KEYCODE_BAC ...
  7. Android APK simple entry application development documentation andbook

    andbook I saw the most simple but the best book entry Android application development, content is only 60 page ...
  8. Chinese version of Android SDK 1.5 (Application base -3)

    1.2 Activity and Task As mentioned earlier, an Activity can start the other, including different application-d ...
  9. [Android development] in the application of write / read information?

    [Android-developers] Reading / writing messages in android application
  10. send message android

    android is very simple to send text messages, In Mainfest.xml first need to add permissions: <uses-permissi ...
  11. Android development examples calendar application integration

    Android calendar application integration development example (reproduced) Schedule is an important function of ...
  12. J2ME programming best practices of a flexible application of RMS

    The standard MIDP application program is the use of persistent RMS. RMS is similar to a small database, Record ...
  13. Android学习笔记--通过Application传递数据代码示例

    使用Application传递数据步骤如下:创建新class,取名MyApp,继承android.app.Application父类,并在MyApp中定义需要保存的属性 在整个Android程序中,有时需要保存某些全局的 ...
  14. Android Browser学习一 application的初始化

    Android Browser 是一个非常好的学习资料, 使用了自己设计的MVC架构,来管理书签, 浏览器 等各个功能,有具有一定的稳定性,知道我们学习 Browser是从Application开始启动的,启动流程如下: ...
  15. Android应用程序变量(Application级别)

    Android应用程序开发中,有的时候我们在应用程序的任何一个地方都需要访问一个全局变量,也就是在任何一个Activity中都可以访问的变量.它不会因为Activity的生命周期结束而消失.要实现应用程序级的变量,我们可 ...
  16. android phone google map application can not display the map

    milestone Congan desk market downloaded the Google Maps application software and my own writing process maps a ...
  17. Android MapView map the application process in apiKey

    If you use the Google map in a blank map, then the following operation is carried out by you. 1, the first gen ...
  18. Android onTouchEvent, onClick, and a call to mechanism onLongClick

    A View on the screen for control, Android should be how to distinguish between the trigger onTouchEvent, or on ...
  19. Learning about Android threads

    1. Android process Before the thread in the understanding of Android Android must first look at the process. W ...