zoukankan      html  css  js  c++  java
  • 怎样在android系统启动时自动运行自己的程序(RECEIVE_BOOT_COMPLETED)

    关于Android3.1后Boot_COMPLETED广播不响应的问题见ALEX的文章:Android3.1后Boot_COMPLETED广播不响应的问题

    感谢ALEX的指正。

    android系统在Manifest.permission中有这样一条RECEIVE_BOOT_COMPLETED的定义,当你自己的程序加入这个权限后,就可以在系统启动完毕后收到一条系统的广播,这个广播的标志为ACTION_BOOT_COMPLETED,因此我们只要定义一个BroadcastReceiver用来接收这个广播,然后加入自定义的动作即可。代码如下:

     

    1. public class LocationLoggerServiceManager extends BroadcastReceiver {  
    2.     public static final String TAG = "customTag";  
    3.     @Override  
    4.     public void onReceive(Context context, Intent intent) {  
    5.         if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {  
    6.             ComponentName comp = new ComponentName(context.getPackageName(), MainActivity.class.getName());  
    7.               
    8.             context.startActivity(new Intent().setComponent(comp).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));  
    9.         } else {  
    10.             Log.e(TAG, "Received unexpected intent " + intent.toString());  
    11.         }  
    12.     }  
    13. }  
     

    在AndroidManifest.xml中加入这个类的定义和权限说明

     

    1. <receiver  
    2.             android:name=".LocationLoggerServiceManager"  
    3.             android:enabled="true"  
    4.             android:exported="false"  
    5.             android:label="LocationLoggerServiceManager">  
    6.             <intent-filter>  
    7.                 <action  
    8.                     android:name="android.intent.action.BOOT_COMPLETED" />  
    9.             </intent-filter>  
    10.         </receiver>  
     

     

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

     

    OK,大功告成。这里演示的是启动一个activity,同理你也可以启动一个service.


    REFERENCES:http://blog.csdn.net/roadog2006/article/details/5477294

    http://blog.csdn.net/alex_hx/article/details/7501374


    ---------------------------------------------------------------------------------------------------------------------------------
    copyright:http://www.cnblogs.com/anee/
  • 相关阅读:
    康托展开
    Linux Command Line Basics
    hihoCoder 1401 Registration
    C++ 参考网站
    Linux 下的常用工具
    SQL 命令
    GNU MAKE 笔记
    一道基本的计算几何题
    uva 1451 平均值
    bzoj 1826 缓存交换
  • 原文地址:https://www.cnblogs.com/anee/p/2675914.html
Copyright © 2011-2022 走看看