设置状态栏

本文介绍了一个音乐播放器应用中如何使用Android的通知栏来控制音乐播放,包括启动播放、暂停以及从通知栏进入音乐播放页面的功能实现。通过创建自定义通知并设置PendingIntent,使得用户可以在通知栏直接操作播放器。
  private void start() {

        mediaPlayer.start();
        //当播放歌曲的时候,在状态显示正在播放,点击的时候,可以进入音乐播放页面
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //最主要
        Intent intent = new Intent(this, AudioPlayerActivity.class);
        intent.putExtra("notification",true);//标识来自状态拦
        PendingIntent pendingIntent = PendingIntent.getActivity(this,1,intent,PendingIntent.FLAG_UPDATE_CURRENT);
        Notification notification = new Notification.Builder(this)
                .setSmallIcon(R.drawable.notification_music_playing)
                .setContentTitle("321音乐")
                .setContentText("正在播放:"+getName())
                .setContentIntent(pendingIntent)
                .build();
        manager.notify(1, notification);
    }
/**
     * 播暂停音乐
     */
    private void pause() {
        mediaPlayer.pause();
        manager.cancel(1);
    }

避免从状态栏进入活动后重新播放歌曲

 private void getData() {
        notification = getIntent().getBooleanExtra("notification", false);
        if(!notification){
            position = getIntent().getIntExtra("position",0);
        }
    }

避免从状态栏进入活动中时重新与服务连接导致执行 service.openAudio(position);
重新进入活动中时没有intent传进来‘position’,此时的position默认为0,所以会导致从头开始播放。

  private ServiceConnection con = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder iBinder) {

            service = IMusicPlayerService.Stub.asInterface(iBinder);
            if (service != null) {
                try {
                    if(!notification){//从列表
                        service.openAudio(position);
                    }else{
                        System.out.println("onServiceConnected==Thread-name=="+Thread.currentThread().getName());
                        //从状态栏
                        showViewData();
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

            if (service != null) {
                try {
                    service.stop();
                    service = null;
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值