需求:有时候,我们需要自己的程序在开机后自动运行;在关机时,记录一些信息到文件中.
一、开机广播监听
Android系统启动完成后会自动发出启动完成广播(android.intent.action.BOOT_COMPLETED),
所有注册了接收启动完成广播的接收器(BroadcastReceiver)都会收到此广播.
①编写一个继承BroadcastReceiver的类,接受系统启动完成广播.
1 package com.example.systemtest; 2 3 import android.content.BroadcastReceiver; 4 import android.content.Context; 5 import android.content.Intent; 6 7 /** 8 * 系统启动完成广播接收器 9 * #<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 10 * @author Lone_Wolf 11 */ 12 public class BootCompletedReceiver extends BroadcastReceiver { 13 @Override 14 public void onReceive(Context context, Intent intent) { 15 if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { 16 //example:启动程序 17 Intent start = new Intent(context, MainActivity.class); 18 start.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 19 context.startActivity(start); 20 } 21 } 22 }
②在AndroidManifest.xml文件里注册广播接收器.
1 <receiver android:name="com.example.systemtest.BootCompletedReceiver" > 2 <intent-filter> 3 <!-- 开机广播 --> 4 <action android:name="android.intent.action.BOOT_COMPLETED" /> 5 </intent-filter> 6 </receiver>
③添加相应权限.
1 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
二、关机广播监听
与开机广播对应,Android系统在即将关闭时发出系统关闭广播(android.intent.action.ACTION_SHUTDOWN).
①编写一个继承BroadcastReceiver的类,接受系统关闭广播.
1 package com.example.systemtest; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 6 import android.content.BroadcastReceiver; 7 import android.content.Context; 8 import android.content.Intent; 9 10 /** 11 * 系统关闭广播接收器 12 * @author Lone_Wolf 13 */ 14 public class ShutdownReceiver extends BroadcastReceiver { 15 @Override 16 public void onReceive(Context context, Intent intent) { 17 if (intent.getAction().equals(Intent.ACTION_SHUTDOWN)) { 18 //example:写入文件 19 FileOutputStream fos; 20 try { 21 fos = new FileOutputStream( 22 android.os.Environment.getExternalStorageDirectory() 23 + File.separator + "SysLog.txt", true); 24 fos.write("系统退出".getBytes("utf-8")); 25 fos.close(); 26 } catch (Exception e) { 27 e.printStackTrace(); 28 } 29 } 30 } 31 }
②在AndroidManifest.xml文件里注册广播接收器.
1 <receiver android:name="com.example.systemtest.ShutdownReceiver" > 2 <intent-filter> 3 <!-- 关机广播 --> 4 <action android:name="android.intent.action.ACTION_SHUTDOWN" /> 5 </intent-filter> 6 </receiver>
注: onReceive中代码的执行时间不要超过5s,否则android会弹出超时dialog.
如果需要做耗时处理,可以在onReceive()里开始一个Service,让Service去做耗时处理.
最好不要用子线程,因为BroadcastReceiver的生命周期很短,子线程可能还没有结束BroadcastReceiver就先结束了.
时间: 2024-10-23 03:13:14