当前位置: 移动技术网 > IT编程>移动开发>Android > android开机自启动原理与实现案例(附源码)

android开机自启动原理与实现案例(附源码)

2019年07月24日  | 移动技术网IT编程  | 我要评论

纪敏尚,淫荡妈妈,月亮代表我的心吉他谱

原理:
android系统通过应用程序自行在系统中登记注册事件(即intent)来响应系统产生的各类消息。 android系统为应用程序管理功能提供了大量的api,通过配置intent和permission来实现各种功能。
开机自启动是通过
<intent-filter>
<action android:name="android.intent.action.boot_completed"/>
<category android:name="android.intent.category.home" />
</intent-filter>
和权限<uses-permission android:name="android.permission.receive_boot_completed"></uses-permission>实现。

举例:
1.新建一个广播接收器的类:[java]
复制代码 代码如下:

/*
* $filename: bootbroadcastreceiver.java,v $
* $date: 2013-6-7 $
* copyright (c) zhenghaibo, inc. all rights reserved.
* this software is made by zhenghaibo.
*/
package njupt.zhb.startyouself;

import android.content.broadcastreceiver;
import android.content.context;
import android.content.intent;

/*
*@author: zhenghaibo
*web: http://blog.csdn.net/nuptboyzhb
*mail: zhb931706659@126.com
*2013-6-7 nanjing,njupt,china
*/
public class bootbroadcastreceiver extends broadcastreceiver {
static final string action_boot="android.intent.action.boot_completed";

@override
public void onreceive(context context, intent intent) {
if (intent.getaction().equals(action_boot)){
intent startintent=new intent(context,mainactivity.class); //接收到广播后,跳转到mainactivity
startintent.addflags(intent.flag_activity_new_task);
context.startactivity(startintent);
}

}

}

2.在manifest.xml文件中注册广播接收机,并且配置权限
注册广播接收机:
复制代码 代码如下:

<!-- 注册系统广播接收器 -->
<receiver android:name=".bootbroadcastreceiver" >
<intent-filter>
<action android:name="android.intent.action.boot_completed"/>
<category android:name="android.intent.category.home" />
</intent-filter>
</receiver>

添加权限:
复制代码 代码如下:

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

完成上述步骤后,启动一次程序,完成注册。等下次手机开机时,该软件即会自动启动。
扩展:不仅可以自动启动activity,也可以启动一个后台服务(service),只需要修改接收机中onreceive函数中的内容即可!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网