Recently, we found that the Message can be used to send parameters. This is a good idea. I wrote an example, clicked on the screen, sent a Message to the Activity, passed two parameters, and destroyed the activity!
Reprinted please indicate the source: http://blog.csdn.net/wdaming1986/article/details/6748688
Open the program interface: Click the screen and destroy the activity to bring up Toast:
Check the Code:
MainActivity. Java class:
Package com.cn. android;
Import android. app. Activity;
Import android. OS. Bundle;
Import android. OS. Handler;
Import android. OS. Message;
Import android. widget. Toast;
Public class MainActivity extends Activity {
Final static int CANSHU = 1;
Public Handler mHandler = new Handler (){
Public void handleMessage (Message msg ){
Switch (msg. what ){
Case CANSHU: String str1 = msg. getData (). getString ("text1"); // accept the parameters passed by msg
String str2 = msg. getData (). getString ("text2"); // accepts the parameters passed by msg.
InitFinishMainActivity (str1, str2 );
Break;
Default: break;
}
}
};
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
InitMainActivity ();
}
Public void InitMainActivity ()
{
SetContentView (new MainActivityView (this, this ));
}
Public void initFinishMainActivity (String str1, String str2)
{
Toast. makeText (MainActivity. this, str1 + str2, Toast. LENGTH_LONG). show ();
Finish ();
}
}
MainActivityView. Java class:
Package com.cn. android;
Import android. content. Context;
Import android. graphics. Bitmap;
Import android. graphics. BitmapFactory;
Import android. graphics. Canvas;
Import android. graphics. Rect;
Import android. OS. Bundle;
Import android. OS. Message;
Import android. view. MotionEvent;
Import android. view. View;
Public class MainActivityView extends View {
Private MainActivity;
Private Context context;
Private Bitmap m_Bitmap;
Public MainActivityView (Context context, MainActivity activity ){
Super (context );
This. activity = activity;
This. context = context;
InitBitmap ();
}
Www.2cto.com
Public void initBitmap ()
{
M_Bitmap = BitmapFactory. decodeResource (this. getResources (), R. drawable. bg );
}
@ Override
Public void onDraw (Canvas canvas ){
Canvas. drawBitmap (m_Bitmap, 0, 0, null );
}
@ Override
Public boolean onTouchEvent (MotionEvent event ){
Int x = (int) event. getX ();
Int y = (int) event. getY ();
Rect rect;
Rect = new Rect (0, 0, 320,480 );
If (rect. contains (x, y ))
{
Message msg = new Message ();
Msg. what = MainActivity. CANSHU;
Bundle bundle = new Bundle ();
Bundle. putString ("text1", "Daming's message passing parameter example! "); // Store data in Bundle
Bundle. putString ("text2", "Time: 2011-09-05"); // put data to Bundle
Msg. setData (bundle); // mes uses Bundle to transmit data
Activity. mHandler. sendMessage (msg); // use handler in activity to send messages
}
Return super. onTouchEvent (event );
}
}