Sometimes we need to modify the data or UI of the activity in a class other than the activity, or modify the values of other classes in the Custom class. This is quite troublesome! At this time, we need a global container to store the data to be shared, just like the session in J2EE. Of course, Android designers must have taken this into consideration. Go to the topic -----> Application)
Usage:
1. Implement your own Applicaiton
public class ApplicationContext extends Application { public static final int FLUSH_MAIN_ACTIVITY=1; private Handler main; public void setMainHandler(Handler handler){ main=handler; } public void flushMain(){ main.sendEmptyMessage(FLUSH_MAIN_ACTIVITY); } }
2. Define handler in activity and register Handler
Package COM. sequel. text; import android. app. activity; import android. app. application; import android. content. intent; import android. OS. bundle; import android. OS. handler; import android. OS. message; public class mainactivity extends activity {private int COUNT = 0;/** called when the activity is first created. * // define handler, Handler flushhandler = new handler () {@ overridepublic void handlemessage (Message MSG) {Switch (MSG. what) {Case applicationcontext. flush_main_activity: // The operation operat (); break; default: break;} super. handlemessage (MSG) ;}}; private applicationcontext APPC; @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); APPC = (applicationcontext) getapplication (); // register handlerappc. setmainhandler (flushhandler); try {thread. sleep (2000);} catch (interruptedexception e) {// todo auto-generated catch blocke. printstacktrace ();} startactivity (new intent (mainactivity. this, secondactivity. class); // start another activity} public void operat (){//..... system. out. println (count ++ );}}
Third, call method ---- perform operations in secondactivity
Import android. app. activity; import android. app. application; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; public class secondactivity extends activity {/** called when the activity is first created. */private applicationcontext APPC; private button; @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. second); button = (button) findviewbyid (R. id. requestbutton); button. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {// todo auto-generated method stub // This is the call method APPC. flushmain () ;}}); APPC = (applicationcontext) getapplication ();}}
Fourth, never think this is all done! Register your own application in androidmanifest. xml
<application android:icon="@drawable/icon" android:label="@string/app_name" android:name=".ApplicationContext">