一.接收系统的分钟广播
TimeReceiver.java
package com.xian.app.broadcast.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import java.util.Date;
public class TimeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent !=null){
Log.i("xian","接收到一个分钟广播"+new Date().toString());
}
}
}
Activity.java
//...省略
@Override
protected void onStart() {
super.onStart()
/****注册分钟接收广播器****/
timeReceiver = new TimeReceiver();
IntentFilter timeFilter = new IntentFilter(Intent.ACTION_TIME_TICK);
registerReceiver(timeReceiver,timeFilter);
/****注册分钟接收广播器****/
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(timeReceiver);
}
//省略
二、震动广播
StockReceiver.java
public class StockReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("xian","Vibrator ***************");
if(intent !=null &&intent.getAction().equals(MainActivity.BROADCAST_SHOCK)){
//从系统服务中获取震动管理器
Vibrator vb = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
vb.vibrate(500);
}
}
}
触发代码
Intent intent = new Intent(BROADCAST_SHOCK);
//8.0后必须制定setComponent方法指定接收器的完整路径
ComponentName componentName = new ComponentName(this,"com.xian.app.broadcast.receiver.StockReceiver");
intent.setComponent(componentName);
sendBroadcast(intent);
静态注册与权限 AndroidManifest.xml
<uses-permission android:name="android.permission.VIBRATE" />
<receiver android:name=".receiver.StockReceiver"
android:exported="true">
<intent-filter>
<action android:name="com.xian.app.broadcast.shock" />
</intent-filter>
</receiver>
标签:void,系统,广播,intent,import,new,Android,Intent
From: https://www.cnblogs.com/paylove/p/18065733