[Android实例] Android实现开机自动运行程序
16lz
2021-01-23
背景知识:当Android启动时,会发出一个系统广播,内容为ACTION_BOOT_COMPLETED,它的字符串常量表示为 android.intent.action.BOOT_COMPLETED。只要在程序中“捕捉”到这个消息,再启动之即可。记住,Android框架说:Don't call me, I'll call you back。我们要做的是做好接收这个消息的准备,而实现的手段就是实现一个BroadcastReceiver。
代码解析:
1、界面Activity:SayHello.java
2、接收广播消息:BootBroadcastReceiver.java
3、配置文件:AndroidManifest.xml
延伸思考:在多数情况下,要自动运行的不是有界面的程序,而是在后台运行的service。此时,就要用startService来启动相应的 service了。
代码解析:
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);
- }
- }
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);
- }
- }
- }
3、配置文件:AndroidManifest.xml
- <?xml version="1.0" encoding="utf-8"?>
- package="com.ghstudio.BootStartDemo"
- android:versionCode="1"
- android:versionName="1.0">
-
- android:label="@string/app_name">
-
-
-
-
-
- [b]
-
-
-
- [/b]
-
-
-
延伸思考:在多数情况下,要自动运行的不是有界面的程序,而是在后台运行的service。此时,就要用startService来启动相应的 service了。
更多相关文章
- Android手机拨打电话、手动发送短信与自动拨打电话、自动发送短
- Android SDK编译 ——如何将自己源代码加入android.jar
- Android Audio代码分析1 - AudioTrack使用示例
- Android 动态加载APK--代码安装、获取资源及Intent调用已安装apk
- Android 中颜色对应的代码集合
- 《Android 编程权威指南》(Android Programming The Big Nerd Ran
- 美团,大众点评,悬浮窗功能代码
- Android 第一行代码