• Android笔记之开机自启


    有时候需要应用具有开机自启的能力,或者更常见的场景是开机时悄悄在后台启动一个Service。

    关键点:

    1. Android系统在开机的时候会发送一条广播消息,只需要接收这条广播消息即可,不过需要注意的是接收开机广播也是需要权限的。

    2. 需要使用静态注册,静态注册在应用没有运行的时候也能够接收广播。

    3. 在接收开机广播的BroadcaseReceiver的onReceive方法中启动Activity可以实现开机启动应用程序,启动一个Service实现开机自启服务。

    下面是一个开机启动应用的例子:

    BootCompleteReceiver.java:

    package cc11001100.androidstudy_002;
    
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    
    public class BootCompleteReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
    
            Intent mainActivityIntent = new Intent(context, MainActivity.class);
            mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(mainActivityIntent);
    
        }
    }
    

    AndroidManifest.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="cc11001100.androidstudy_002">
    
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
        
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
            <receiver
                android:name=".BootCompleteReceiver"
                android:enabled="true"
                android:exported="true">
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                </intent-filter>
            </receiver>
        </application>
    
    </manifest>

    .

  • 相关阅读:
    软件测试工具
    nat 转发
    修改Oracle 10g Express Edition的字符集
    java数字证书学习笔记
    【Java–XML】JDOM解析XML字符串(非XML文档)
    JAVA Web快速开发部署(Javarebel实现真正高效的tomcat热部署)
    热天稀饭配方
    javascript 使用正则实现replaceall功能
    设置eclipse中各类型文件的默认浏览器(如设置flex的.mxml的编辑器为MXML Editor)
    GAE中JDO数据清除
  • 原文地址:https://www.cnblogs.com/cc11001100/p/9065471.html
Copyright © 2020-2023  润新知