zoukankan      html  css  js  c++  java
  • 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>

    .

  • 相关阅读:
    MySQL聚集索引和非聚集索引
    如何避免表单重复提交
    i++为什么是线程不安全的
    TIME_WAIT和CLOSE_WAIT
    TCP三次握手四次挥手
    get和post区别
    Session存储
    Session和Cookie的区别和联系
    Servlet与线程安全
    AQS
  • 原文地址:https://www.cnblogs.com/cc11001100/p/9065471.html
Copyright © 2011-2022 走看看