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);
}
}