Android 使用广播系统解决app开机自启动问题

源码Demo获取方法

关注 【网罗开发】微信公众号,回复【160】便可领取。
网罗天下方法,方便你我开发,更多Android技术干货等待领取,所有文档会持续更新,欢迎关注一起成长!

总结一下使用ACTION_BOOT_COMPLETED的广播,解决app开机自启动的问题
1.首先在你的工程上建一个广播接受的类,继承BroadcastReceiver:

package guide.example.com.guidedemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

/**
 * Created by fby on 2017/6/26.
 */

public class BootReceiver extends BroadcastReceiver {
    static final String action_boot ="android.intent.action.BOOT_COMPLETED";

    @Override
    public void onReceive (Context context, Intent intent) {

        Log.i("charge start", "启动完成");

        if (intent.getAction().equals(action_boot)){

            Intent mBootIntent = new Intent(context, MainActivity.class);
            // 下面这句话必须加上才能开机自动运行app的界面
            mBootIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(mBootIntent);
        }
    }
}

2.然后要在AndroidManifest.xml中加入权限和配置相关信息:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />  

3.在application标签中,配置以下相关信息:

//BootReceiver是上面建的广播类
        <receiver android:name=".BootReceiver">  
            <intent-filter>  
                <!--注册开机广播地址-->  
                <action android:name="android.intent.action.BOOT_COMPLETED">            
                </action>  

                <category android:name="android.intent.category.DEFAULT" />  
            </intent-filter>  
        </receiver>  

补充说明:
1.查看系统中是否安装了类似360管家的软件,为了加快开机速度,默认是关闭掉开机广播的,只需要在设置中打开即可。
2.如果监听不到广播,可以尝试同时监听广播和sd卡。
3.同时监听广播和sd卡,在application标签中,配置以下相关信息:

    <receiver android:name=".broadcastReceiver.BootCompletedReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />

                <category android:name="android.intent.category.HOME" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_ADDED" />
                <action android:name="android.intent.action.PACKAGE_REMOVED" />
                <action android:name="android.intent.action.PACKAGE_REPLACED" />

                <data android:scheme="package" />
            </intent-filter>

        </receiver>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,948评论 18 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,349评论 25 708
  • 现实中的广播:电台为了传达一些消息而发送广播,通过广播携带要传达的消息,群众只要买一个收音机,就可以收到广播了。 ...
    stevewang阅读 4,296评论 0 8
  • 感恩宇宙赐予我的一切,感恩我接受一切,感恩父母养育之恩,感恩金钱宝宝可以让我孝敬父母,感恩和谐的社会提供的就业平台...
    liuxiaorui阅读 116评论 0 0
  • 不觉已近中秋,忆及往昔佳节总是与父母一同度过,总不至感到丝许苦寂,现在在离家三四千公里的地方,同是一轮明月...
    莫道桑榆晚见天阅读 202评论 0 0