详解Android中BroadCastReceiver组件

2019-12-10 18:57:11王旭

1.开机启动服务

我们经常会有这样的应用场合,比如消息推送服务,需要实现开机启动的功能。要实现这个功能,我们就可以订阅系统“启动完成”这条广播,接收到这条广播后我们就可以启动自己的服务了。我们来看一下BootCompleteReceiver和MsgPushService的具体实现:

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

public class BootCompleteReceiver extends BroadcastReceiver { 

  private static final String TAG = "BootCompleteReceiver"; 

  @Override 
  public void onReceive(Context context, Intent intent) { 
    Intent service = new Intent(context, MsgPushService.class); 
    context.startService(service); 
    Log.i(TAG, "Boot Complete. Starting MsgPushService..."); 
  } 

} 

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

public class MsgPushService extends Service { 

  private static final String TAG = "MsgPushService"; 

  @Override 
  public void onCreate() { 
    super.onCreate(); 
    Log.i(TAG, "onCreate called."); 
  } 

  @Override 
  public int onStartCommand(Intent intent, int flags, int startId) { 
    Log.i(TAG, "onStartCommand called."); 
    return super.onStartCommand(intent, flags, startId); 
  } 

  @Override 
  public IBinder onBind(Intent arg0) { 
    return null; 
  } 
} 

然后我们需要在AndroidManifest.xml中配置相关信息:

<!-- 开机广播接受者 --> 
<receiver android:name=".BootCompleteReceiver"> 
  <intent-filter> 
    <!-- 注册开机广播地址--> 
    <action android:name="android.intent.action.BOOT_COMPLETED"/> 
    <category android:name="android.intent.category.DEFAULT" /> 
  </intent-filter> 
</receiver> 
<!-- 消息推送服务 --> 
<service android:name=".MsgPushService"/>