程序进入后,先执行Application.onCreate(),再执行Activity.onCreate()。如果没有生成自己的Application,那么系统会为你自动生成一个。
退出程序时我们一般只调用finish()函数杀死当前Activity,Application退到幕后,由系统自动维护。
再次启动程序时就不会执行Application.onCreate(),而是直接执行Activity.onCreate()。
我的程序需要退出程序时,不但杀死Activity,而且也干掉主Application。网上搜索了一阵,发现只要两条语句就可以。
ActivityManager activityMgr = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
activityMgr.restartPackage(getPackageName());
还要加入权限
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
参考文章:http://chenzoudgh.blog.163.com/blog/static/149868996201010259141434/
上面的版本只对2.1及以前版本有效,2.2以后要使用killBackgroundProcesses,我用2.3的机器试过发现无效。我的程序中就把网上的一些说法全用了。代码如下:
public void exitPro(){
//杀死后台服务
//手机版本
AggLog.log(TAG,"HAITEST013:exitPro Build.VERSION.RELEASE=" +Build.VERSION.RELEASE);
Intent i = new Intent();
i.setClass(this, MyService.class);
this.stopService(i);
//杀死Application
String packName = getPackageName();
ActivityManager activityMgr = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
activityMgr.restartPackage(packName);//需要权限<uses-permission android:name="android.permission.RESTART_PACKAGES" />
activityMgr.killBackgroundProcesses(packName);//需要权限 <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>
android.os.Process.killProcess(android.os.Process.myPid());
}
AndroidManifest.xml添加权限
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>
新版本在2.1与2.3测试都通过。
写代码测试了一下Activity,Application,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在Context.bindService和context.unBindService()里用到
private ServiceConnection mServiceConnection = new ServiceConnection() {
//当我bindService时,让TextView显示MyService里getSystemTime()方法的返回值
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());
//杀死Application
ActivityManager activityMgr = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
activityMgr.restartPackage(getPackageName());
//杀死当前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: 上午2:05
* To change this template use File | Settings | File Templates.
*/
public class MyService extends Service {
//定义个一个Tag标签
private static final String TAG = "TestDemo.MyService";
//这里定义吧一个Binder类,用在onBind()有方法里,这样Activity那边可以获取到
private MyBinder mBinder = new MyBinder();
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG, "start IBinder~~~");
return mBinder;
}
@Override
public void onCreate() {
Log.e(TAG, "start onCreate~~~");
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
Log.e(TAG, "start onStart~~~");
super.onStart(intent, startId);
}
@Override
public void onDestroy() {
Log.e(TAG, "start onDestroy~~~");
super.onDestroy();
}
@Override
public boolean onUnbind(Intent intent) {
Log.e(TAG, "start onUnbind~~~");
return super.onUnbind(intent);
}
//这里我写了一个获取当前时间的函数,不过没有格式化就先这么着吧
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: 上午5:17
* 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配置文件:
<?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"
>
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="hello"
/>
<Button
android:id="@+id/startservice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="startService"
/>
<Button
android:id="@+id/stopservice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="stopService"
/>
<Button
android:id="@+id/bindservice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="bindService"
/>
<Button
android:id="@+id/unbindservice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="unbindService"
/>
</LinearLayout>
AndroidManifest.xml文件
<?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>