先上效果图:来短信时音乐响起
核心代码如下:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button btnStop;
private boolean isCast; //是否为广播激活
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{"android.permission.RECEIVE_SMS"},1);
}
btnStop=findViewById(R.id.btnStop);
Intent intent = getIntent(); //获取广播意图对象
isCast = intent.getBooleanExtra("iscast", false); //默认值为false
btnStop.setEnabled(isCast); //设置停止按钮可用和单击监听
if(isCast) Toast.makeText(this, "正在播放音乐...", Toast.LENGTH_SHORT).show();
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
//显式服务调用意图(非绑定式)
Intent intent=new Intent(MainActivity.this,MyAudioService.class);
//在Activity组件里,停止音乐播放服务
stopService(intent);
finish(); //销毁本活动
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 1:
if(grantResults[0]!=PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "未授权,无法实现预定的功能!", Toast.LENGTH_SHORT).show();
finish();
}else{
Toast.makeText(this, "请发一条短信验证...", Toast.LENGTH_SHORT).show();
}
}
}
}
MyAudioService.java
AudioService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
//throw new UnsupportedOperationException("Not yet implemented");
return null;
}
public void onCreate() {
mediaPlayer = MediaPlayer.create(this,R.raw.love);
mediaPlayer.start();
}
@Override
public void onDestroy() {
mediaPlayer.stop();
}
}
SmsReceiver.java
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
//throw new UnsupportedOperationException("Not yet implemented");
Intent serviceIntent = new Intent(context, MyAudioService.class);
//在广播组件里,通过上下文对象启动音乐播放服务组件
context.startService(serviceIntent);
//新建调用Activity组件的意图
Intent activityIntent = new Intent(context, MainActivity.class);
activityIntent.putExtra("iscast", true); //携带数据
//新建栈用来存放被启动的Activity(当已经存在时,只做移动处理)
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//在广播组件里,通过上下文对象启动Activity组件
context.startActivity(activityIntent);
}
}
完整代码已上传至码云:https://gitee.com/zhangjianhui1010/BroadcastAndServer.git
参考资源:http://www.wustwzx.com/as/sy/sy06.html#mk1