需求:有时候,我们需要自己的程序在开机后自动运行;在关机时,记录一些信息到文件中.

一、开机广播监听
Android系统启动完成后会自动发出启动完成广播(android.intent.action.BOOT_COMPLETED),
所有注册了接收启动完成广播的接收器(BroadcastReceiver)都会收到此广播.

①编写一个继承BroadcastReceiver的类,接受系统启动完成广播.

package com.example.systemtest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/**
 * 系统启动完成广播接收器
 * #<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
 * @author Lone_Wolf
 */
public class BootCompletedReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
            //example:启动程序
            Intent start = new Intent(context, MainActivity.class);
            start.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//
            context.startActivity(start);
        }
    }
}



②在AndroidManifest.xml文件里注册广播接收器.


<receiver android:name="com.example.systemtest.BootCompletedReceiver" >  
    <intent-filter>   
        <!-- 开机广播 -->  
        <action android:name="android.intent.action.BOOT_COMPLETED" />  
    </intent-filter>   
</receiver>


③添加相应权限.


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


 

二、关机广播监听
与开机广播对应,Android系统在即将关闭时发出系统关闭广播(android.intent.action.ACTION_SHUTDOWN).

①编写一个继承BroadcastReceiver的类,接受系统关闭广播.



package com.example.systemtest;

import java.io.File;
import java.io.FileOutputStream;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/**
 * 系统关闭广播接收器
 * @author Lone_Wolf
 */
public class ShutdownReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SHUTDOWN)) {
            //example:写入文件
            FileOutputStream fos;
            try {
                fos = new FileOutputStream(
                          android.os.Environment.getExternalStorageDirectory()
                          + File.separator + "SysLog.txt", true);
                fos.write("系统退出".getBytes("utf-8"));
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }           
        }
    }
}



②在AndroidManifest.xml文件里注册广播接收器.


<receiver android:name="com.example.systemtest.ShutdownReceiver" >  
    <intent-filter>   
        <!-- 关机广播 -->  
        <action android:name="android.intent.action.ACTION_SHUTDOWN" />  
    </intent-filter>   
</receiver>


 

注: onReceive中代码的执行时间不要超过5s,否则android会弹出超时dialog.
     如果需要做耗时处理,可以在onReceive()里开始一个Service,让Service去做耗时处理.
     最好不要用子线程,因为BroadcastReceiver的生命周期很短,子线程可能还没有结束BroadcastReceiver就先结束了.