Android开机自动运行服务

154 篇文章 0 订阅
有些时候,应用需要在开机时就自动运行,例如某个自动从网上更新内容的后台 service 。怎样实现开机自动运行的应用?在撰写本文时,联想到高焕堂先生以“ Don''t call me, I''ll call you back!” 总结 Android 框架,真是说到点子上了。理解这句话的含义,许多有关 Android 平台上实现某种功能的问题,都能迎刃而解。 使用场景:手机开机后,自动运行程序,在屏幕上显示 "Hello. I started!" 字样。 背景知识:当 Android 启动时,会发出一个系统广播,内容为 ACTION_BOOT_COMPLETED ,它的字符串常量表示为 android.intent.action.BOOT_COMPLETED 。只要在程序中“捕捉”到这个消息,再启动之即可。记住, Android 框架说: Don''t call me, I''ll call you back 。我们要做的是做好接收这个消息的准备,而实现的手段就是实现一个 BroadcastReceiver 代码解析: 1 、界面 Activity SayHello.java
package com.ghstudio.BootStartDemo;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class SayHello extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("Hello. I started!");
setContentView(tv);
}
}
这段代码很简单,当 Activity 启动时,创建一个 TextView ,用它显示 "Hello. I started!" 字样。 2 、接收广播消息: BootBroadcastReceiver.java
package com.ghstudio.BootStartDemo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootBroadcastReceiver extends BroadcastReceiver {
static final String ACTION = "android.intent.action.BOOT_COMPLETED";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION)){
Intent sayHelloIntent=new Intent(context,SayHello.class);
sayHelloIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(sayHelloIntent);
}
}
}
该类派生自 BroadcastReceiver ,覆载方法 onReceive 中,检测接收到的 Intent 是否符合 BOOT_COMPLETED ,如果符合,则启动 SayHello 那个 Activity 3 、配置文件: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ghstudio.BootStartDemo"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".SayHello"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".BootBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
<uses-sdk android:minSdkVersion="3" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
</manifest>
注意其中红色粗体字那一部分,该节点向系统注册了一个 receiver ,子节点 intent-filter 表示接收 android.intent.action.BOOT_COMPLETED 消息。不要忘记配置 android.permission.RECEIVE_BOOT_COMPLETED 权限。 完成后,编译出 apk 包,安装到模拟器或手机中。关机,重新开机。




这就是一个广播嘛,用一个 receiver 接受 RECEIVE_BOOT_COMPLETED 这个广播事件,然后就开机就启动这个 app
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值