android 服务自动运行怎么办,Android服务开机自动运行

在Android4.0之前,服务是可以在开机时自动运行的,但是在Android4.0以后,为了安全起见,防止一些非法的后台服务在开机后自动运行,用户必须打开一个Activity后才可以启动服务。

那么我们想想,如果我们不是做一些非法的操作是否可以有其他的变通方法解决这个问题呢。

如果是要更新桌面小组件的数据,那么我们可以在小组件服务创建时启动数据更新服务,如下:

Java

public class NoteWidgetService extends RemoteViewsService {

@Override

public void onCreate() {

Intent intent = new Intent(getApplicationContext(), CloudNoteService.class);

getApplicationContext().startService(intent);

super.onCreate();

}

}

1

2

3

4

5

6

7

8

9

publicclassNoteWidgetServiceextendsRemoteViewsService{

@Override

publicvoidonCreate(){

Intentintent=newIntent(getApplicationContext(),CloudNoteService.class);

getApplicationContext().startService(intent);

super.onCreate();

}

}

*

Android4.0之前设置服务开机自启动的方法

首先AndroidManifest.xml中加入

XHTML

1

创建用于接收RECEIVE_BOOT_COMPLETED广播的BroadcastReceiver类

Java

public class NoteBootReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context arg0, Intent arg1) {

Intent servicentent = new Intent(arg0, CloudNoteService.class);

arg0.startService(servicentent);

}

}

1

2

3

4

5

6

7

8

9

10

publicclassNoteBootReceiverextendsBroadcastReceiver{

@Override

publicvoidonReceive(Contextarg0,Intentarg1){

Intentservicentent=newIntent(arg0,CloudNoteService.class);

arg0.startService(servicentent);

}

}

在AndroidManifest.xml中声明这个receiver类

XHTML

android:name="com.jeoe.cloudnote.NoteBootReceiver"

android:enabled="true"

android:exported="true"

android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >

1

2

3

4

5

6

7

8

9

10

11

12

android:name="com.jeoe.cloudnote.NoteBootReceiver"

android:enabled="true"

android:exported="true"

android:permission="android.permission.RECEIVE_BOOT_COMPLETED">

BOOT_COMPLETED:当系统启动完成时发送这个广播

QUICKBOOT_POWERON:HTC的一些手机有快速启动,这个action是针对快速启动情况的

ACTION_EXTERNAL_APPLICATIONS_AVAILABLE:这个action是针对程序安装到sd卡的时候,sd卡上的应用加载完成时发送此广播

打赏

f69872ab5631b766bfb8c62b6b7d28fa.png微信扫一扫,打赏作者吧~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值