您的位置:首页 > 其它

安卓学习笔记1——service开机自启动

2014-03-02 16:02 351 查看
例程代码:点击打开链接

本文参考了 好像睡觉.... 的博文点击打开链接

在平时开发中我们可能会遇到需要开机自启动app的某项服务,使其在后台运行。我们在手机刚开机的时候可以查看正在运行的应用,可以看到

比如qq,微信等应用已在后台运行,而这则需要使用android的广播机制来完成。

实现服务的开机自启动主要有三点:

1.创建需要开机自启动的服务,这里为了能便于观察,在该服务中我们呢使其在通知栏打印消息

public class autoBoot extends Service{

private NotificationManager notificationManager=null;
private Notification notification = null;

@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}

@Override
public void onCreate() {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notification = new Notification(R.drawable.ic_launcher, "服务已经自启动", System.currentTimeMillis());
PendingIntent pendingIntent = PendingIntent.getActivity(autoBoot.this ,0,new Intent(autoBoot.this, MainActivity.class) , 0);
notification.setLatestEventInfo(autoBoot.this, "自启动", "服务已经自启动", pendingIntent);
notification.flags= Notification.FLAG_AUTO_CANCEL;
notification.defaults=Notification.DEFAULT_SOUND;
notificationManager.notify(0, notification);

super.onCreate();
}

}
在androidMainfest中完成对该服务的注册,需要注意与普通service不同,需要开机自启动的service必须加上标识,否则接收器中的intent会找不到该服务

而该标识即为<intent-filter>中的<action android:name=""> 因此这个标签不能省略,否则无法实现开机自启动。

<service android:name="com.example.bootstart.autoBoot">
<intent-filter>
<action android:name="com.example.bootstart.autoBoot"/>

<category android:name="android.intent.category.DEFAULT"/>

</intent-filter>
</service>


2.创建广播接收器类,使其extends from BroadcastReceiver

public class bootReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context arg0, Intent arg1) {
Intent newIntent = new Intent("com.example.bootstart.autoBoot");
arg0.startService(newIntent);
//启动com.example.bootstart.autoBoot服务
}

}


并在AndroidMainfest文件中完成对该receiver的注册,在receiver中priority代表优先级,数字越大,优先级越高,这里的数字代表最大优先级,action标签代表该receiver能够接受到的广播行为。这里的注册方法为静态注册,还可以动态注册receiver,虽然我目前还没有尝试过,据说动态注册的优先级要比静态注册的优先级要高,关于动态注册可以参考博文:点击打开链接

<receiver android:name="com.example.bootstart.bootReceiver">
<intent-filter android:priority="2147483647">
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>


3. 在androidMainfest中加上开机自启动的权限

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


完成以上三步即可实现开机自启动,已经过真机测试。


好想睡觉……


好想睡觉……


好想睡觉……

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: