• Service随系统启动运行


    Android系统启动时,会发出android.intent.action.BOOT_COMPLETED广播,定义一个类继承自BroadcastReceiver,监听该广播,并在收到该广播时启动Service,就可以实现在系统启动时运行Service。

    如定义类BroadReceiver继承自BroadcastReceiver,在Manifest文件中定义:

    		<receiver android:name=".BroadReceiver">
    			<intent-filter>
    				<!-- 过滤系统启动广播 -->
    				<action android:name="android.intent.action.BOOT_COMPLETED"/>
    			</intent-filter>
    		</receiver>
    

    该类能够接收到android.intent.action.BOOT_COMPLETED广播。

    Java文件:

    public class BroadReceiver extends BroadcastReceiver{	
    	
    	public void onReceive(Context context, Intent intent){	
    			
    		// 收到系统启动广播后
    		if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()))
    		{
    			// 启动MainService
    			Intent i1 = new Intent(context, MainService.class);
    			context.startService(i1);
    		}
    
    		
    	}
    

    收到消息后,判断是否是android.intent.action.BOOT_COMPLETED消息,如果是,则用startService()方法启动Service。

  • 相关阅读:
    程序写法
    2011年C++再次给力
    WIN7+LINUX双系统
    随机洗牌算法
    Eclipse快捷键大全
    Android 编程规范
    android Context 上下文的几点解析
    消息模式Toast.makeText的几种常见用法
    Eclipse的优化
    用PULL解析器解析XML文件
  • 原文地址:https://www.cnblogs.com/mstk/p/3632623.html
Copyright © 2020-2023  润新知