接受系统广播消息 BroadcastReceiver

BroadcastReceiver 除了接受用户发送的广播之外,还有一个重要的用途 : 接受系统广播.

Android 中 常见的广播Action 常量 :


    ACTION_TIME_TICK
    ACTION_TIME_CHANGED
    ACTION_TIMEZONE_CHANGED
    ACTION_BOOT_COMPLETED   系统启动完成.
    ACTION_PACKAGE_ADDED
    ACTION_PACKAGE_CHANGED
    ACTION_PACKAGE_REMOVED 系统的包被删除.
    ACTION_PACKAGE_RESTARTED
    ACTION_PACKAGE_DATA_CLEARED
    ACTION_UID_REMOVED
    ACTION_BATTERY_CHANGED
    ACTION_POWER_CONNECTED
    ACTION_POWER_DISCONNECTED
    ACTION_SHUTDOWN 

开机自动运行的Service

为了让Service 随系统启动自动运行,可以让 BroadcastReceiver 监听的Action 为 ACTION_BOOT_COMPLETED 常量的 Intent.然后在 BroadcastReceiver 中启动特定的 service.


自定义的广播接收者

package com.test.lunchservice;

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

public class LaunchReceiver extends BroadcastReceiver {
    public LaunchReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.

        Intent intent2 = new Intent(context,LaunchService.class);

        //启动 指定的 Service
        context.startService(intent2);

    }
}

开启的服务

package com.test.lunchservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class LaunchService extends Service {
    public LaunchService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }@Override
     public void onCreate()
    {


        // 定义1秒执行一行输出
        new Timer().schedule(new TimerTask()
        {

            @Override
            public void run()
            {
                System.out.println("-com.test.lunchservice-"
                        + new Date() + "-----");
            }
        }, 0, 2000);
    }
}

主界面

package com.test.lunchservice;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent();
        intent.setAction("android.intent.action.BOOT"); //自定义 action
        sendBroadcast(intent);

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值