zoukankan      html  css  js  c++  java
  • App实现开机启动

    Android启动时,会发出一个系统广播 ACTION_BOOT_COMPLETED,它的字符串常量表示为 “android.intent.action.BOOT_COMPLETED”

    开机自启动程序,只需要“捕捉”到这个消息再启动你的程序即可,我们要做的是接收这个消息,并实现一个BroadcastReceiver。

    1.添加一个自定义广播类 BootReceiver

    public class BootReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {     // boot
                Intent intent2 = new Intent(context, MainActivity.class);
    //          intent2.setAction("android.intent.action.MAIN");
    //          intent2.addCategory("android.intent.category.LAUNCHER");
                intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent2);
            }
        }
    }

    2.在AndroidManifest.xml中Application节点内,添加自定义的广播类和权限:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.moumou.sharedpreferencetest">
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />  //权限
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            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=".BootReceiver" >  //自定义广播类
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </receiver>
        </application>
    </manifest>
  • 相关阅读:
    2015年第5本(英文第4本):Death on the Nile尼罗河上的惨案
    2015年第4本(英文第3本):Godfather教父
    2015年第3本(英文第2本):Daughter of Deceit
    2015年第2本(英文第1本):《The Practice of Programming》
    2015年第1本读书行动笔记:《把你的英语用起来》
    GTD桌面2.0
    独立博客开张!有关读书、GTD和IT方面的内容将发布在新网站上
    2015计划
    Swift
    Swift
  • 原文地址:https://www.cnblogs.com/laoyimou/p/7301671.html
Copyright © 2011-2022 走看看