Android--广播和服务的应用

先上效果图:来短信时音乐响起
在这里插入图片描述
核心代码如下:
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值