receiver的编写
public class ShockReceiver extends BroadcastReceiver {public static final String SHOCK_ACTION = "com.example.myapplication.android_tut.shock";@Overridepublic void onReceive(Context context, Intent intent) {if (intent.getAction().equals(ShockReceiver.SHOCK_ACTION)) {Vibrator vb = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);vb.vibrate(500);}}
}
注册在manifest
<uses-permission android:name="android.permission.VIBRATE" />
<receiverandroid:name=".receiver.ShockReceiver"android:enabled="true"android:exported="true"><intent-filter><action android:name="com.example.chapter04.shock" /></intent-filter>
</receiver>
测试activity
public class Ch3_BroadStaticActivity extends AppCompatActivity implements View.OnClickListener {@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_broad_static_ch3);findViewById(R.id.ch3_btn_send_shock).setOnClickListener(this);}@Overridepublic void onClick(View v) {if (v.getId() == R.id.ch3_btn_send_shock) {String receiverPath = "com.example.myapplication.android_tut.receiver.ShockReceiver";Intent intent = new Intent(ShockReceiver.SHOCK_ACTION);ComponentName componentName = new ComponentName(this, receiverPath);intent.setComponent(componentName);sendBroadcast(intent); Toast.makeText(this, "已发送震动广播", Toast.LENGTH_SHORT).show();}}
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><Buttonandroid:id="@+id/ch3_btn_send_shock"android:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="center"android:text="发送震动广播"android:textColor="@color/black"android:textSize="17sp" /></LinearLayout>
点击按钮震动成功