Android disables application and service establishment

Source: Internet
Author: User

After the program enters, run application. oncreate () and then activity. oncreate (). If you do not generate your own application, the system automatically generates one for you.

When exiting the program, we generally only call the finish () function to kill the current activity. The application is automatically maintained by the system after it exits.

When the program is started again, application. oncreate () is not executed, but activity. oncreate () is executed directly ().

When my program needs to exit the program, it not only kills the activity, but also the main application. After searching for a while on the Internet, we found that we only needed two statements.

                ActivityManager activityMgr = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);                activityMgr.restartPackage(getPackageName());

Add Permissions

    <uses-permission android:name="android.permission.RESTART_PACKAGES" />

Reference: http://chenzoudgh.blog.163.com/blog/static/149868996201010259141434/

The above version is only valid for versions 2.1 and earlier. killbackgroundprocesses will be used later than 2.2. I have tried it on machines 2.3 and found that it is invalid. I used all the online statements in my program. The Code is as follows:

Public void exitpro () {// kill the background service // mobile version agglog. log (TAG, "haitest013: exitpro build. version. release = "+ build. version. release); intent I = new intent (); I. setclass (this, myservice. class); this. stopservice (I); // kill application string packname = getpackagename (); activitymanager activitymgr = (activitymanager) This. getsystemservice (activity_service); activitymgr. restartpackage (packname); // The permission <uses-Permission Android: Name = "android. permission. restart_packages "/> activitymgr. killbackgroundprocesses (packname); // The permission <uses-Permission Android: Name = "android. permission. kill_background_processes "/> android. OS. process. killprocess (Android. OS. process. mypid ());}

Androidmanifest. xml add permissions

    <uses-permission android:name="android.permission.RESTART_PACKAGES" />    <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>

Both the 2.1 and 2.3 versions passed the test.

Write code to test the lifecycle of activity, application, and service:

Package COM. tutor. servicedemo; import android. app. activity; import android. app. activitymanager; import android. content. componentname; import android. content. context; import android. content. intent; import android. content. serviceconnection; import android. OS. bundle; import android. OS. ibinder; import android. util. log; import android. view. keyevent; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. textview; import static android. view. keyevent. keycode_back; public class mytest extends activity implements onclicklistener {Private Static final string tag = "testdemo. mytest "; private myservice mmyservice; private textview mtextview; private button startservicebutton; private button stopservicebutton; private button bindservicebutton; private button unbindservicebutton; private context mcontext; // serviceconnection must be used in context. bindservice and context. in unbindservice (), private serviceconnection mserviceconnection = new serviceconnection () {// when I bindservice, let textview display the return value of the getsystemtime () method in myservice public void onserviceconnected (componentname name, ibinder Service) {// todo auto-generated method stub mmyservice = (myservice. mybinder) Service ). getservice (); mtextview. settext ("I am frome service:" + mmyservice. getsystemtime (); log. E (TAG, "onserviceconnected");} public void onservicedisconnected (componentname name) {// todo auto-generated method stub log. E (TAG, "onservicedisconnected") ;}}; public void oncreate (bundle savedinstancestate) {log. E (TAG, "oncreate"); super. oncreate (savedinstancestate); setcontentview (R. layout. main); setupviews ();} public Boolean onkeydown (INT keycode, keyevent event) {Switch (keycode) {Case keycode_back: log. E (TAG, "getpackagename;" + getpackagename (); // kill application activitymanager activitymgr = (activitymanager) This. getsystemservice (activity_service); activitymgr. restartpackage (getpackagename (); // kill the current activity finish (); Return true; default: break;} return Super. onkeydown (keycode, event);} public void setupviews () {mcontext = mytest. this; mtextview = (textview) findviewbyid (R. id. text); startservicebutton = (button) findviewbyid (R. id. startservice); stopservicebutton = (button) findviewbyid (R. id. stopservice); bindservicebutton = (button) findviewbyid (R. id. bindservice); unbindservicebutton = (button) findviewbyid (R. id. unbindservice); startservicebutton. setonclicklistener (this); stopservicebutton. setonclicklistener (this); bindservicebutton. setonclicklistener (this); unbindservicebutton. setonclicklistener (this);} public void onclick (view v) {// todo auto-generated method stub if (V = startservicebutton) {intent I = new intent (); I. setclass (mytest. this, myservice. class); mcontext. startservice (I);} else if (V = stopservicebutton) {intent I = new intent (); I. setclass (mytest. this, myservice. class); mcontext. stopservice (I);} else if (V = bindservicebutton) {intent I = new intent (); I. setclass (mytest. this, myservice. class); mcontext. bindservice (I, mserviceconnection, bind_auto_create);} else {mcontext. unbindservice (mserviceconnection );}}}

Package COM. tutor. servicedemo; import android. app. service; import android. content. intent; import android. OS. binder; import android. OS. ibinder; import android. text. format. time; import android. util. log; import Java. security. provider;/*** created by intellij idea. * User: Wulong * Date: 11-12-1 * Time: am * to change this template use file | Settings | file templates. */public class myservice extends se Rvice {// define a tag Private Static final string tag = "testdemo. myservice "; // define a binder class here, which is used in the onbind () method, so that the activity side can obtain private mybinder mbinder = new mybinder (); @ overridepublic ibinder onbind (intent) {log. E (TAG, "Start ibinder ~~~ "); Return mbinder ;}@ overridepublic void oncreate () {log. E (TAG," Start oncreate ~~~ "); Super. oncreate () ;}@ overridepublic void onstart (intent, int startid) {log. E (TAG," Start onstart ~~~ "); Super. onstart (intent, startid) ;}@ overridepublic void ondestroy () {log. E (TAG," Start ondestroy ~~~ "); Super. ondestroy () ;}@ overridepublic Boolean onunbind (intent) {log. E (TAG," Start onunbind ~~~ "); Return Super. onunbind (intent) ;}// here I wrote a function to get the current time, but it is not formatted. Public String getsystemtime () {time t = new time (); t. settonow (); log. E (TAG, "getsystemtime =" + T. tostring (); Return T. tostring ();} public class mybinder extends binder {myservice getservice () {return myservice. this ;}}}

Package COM. tutor. servicedemo; import android. app. application; import android. text. HTML; import android. util. log;/*** created by intellij idea. * User: Wulong * Date: 11-12-1 * Time: am * to change this template use file | Settings | file templates. */public class myserviceapplication extends application {public static final string tag = "testdemo. myserviceapplication "; @ override public void oncreate () {super. oncreate (); log. E (TAG, "oncreate") ;}@ override public void onterminate () {super. onterminate (); log. E (TAG, "onterminate");} public void onconfigurationchanged () {log. E (TAG, "onconfigurationchanged ");}}

Main. xml configuration file:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><TextViewandroid:id="@+id/text"      android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="hello"    /><Buttonandroid:id="@+id/startservice"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="startService"/><Buttonandroid:id="@+id/stopservice"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="stopService"/><Buttonandroid:id="@+id/bindservice"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="bindService"/><Buttonandroid:id="@+id/unbindservice"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="unbindService"/></LinearLayout>

Androidmanifest. xml file

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.tutor.servicedemo"      android:versionCode="1"      android:versionName="1.0">    <application android:label="@string/app_name"            android:name=".MyServiceApplication">        <activity android:name=".MyTest"                  android:label="@string/app_name">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <service android:name=".MyService" android:exported="true"></service>      </application>    <uses-permission android:name="android.permission.RESTART_PACKAGES" /></manifest> 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.