android 安卓java视频播放后台暂停不工作请告诉我怎么解决

jchrr9hc  于 2023-04-04  发布在  Android
关注(0)|答案(1)|浏览(72)

MainActivity.java

@SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        IntentFilter powerButtonOff = new IntentFilter(Intent.ACTION_SCREEN_OFF);
        IntentFilter powerButtonOn = new IntentFilter(Intent.ACTION_SCREEN_ON);

        registerReceiver(powerButtonOnOff, powerButtonOff);
        registerReceiver(powerButtonOnOff, powerButtonOn);

MainActivity.java

private void unregisterBroadcast(){
        unregisterReceiver(powerButtonOnOff);
    }

    BroadcastReceiver powerButtonOnOff = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(mediaPlayer == null){
                mediaPlayer = MediaPlayer.create(context,R.id.videoView);
            }
            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                try {
                    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                        mediaPlayer.stop();
                        mediaPlayer.release();
                        mediaPlayer = null;

                    } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                        mediaPlayer.start();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

MainActivity.java

@Override
    protected void onDestroy() {
      unregisterBroadcast();

AndroidManifest.xml

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.DEVICE_POWER"
        tools:ignore="ProtectedPermissions" />

    <uses-permission android:name="android.permission.WAKE_LOCK"/>

你好。上面的代码应该在手机关机的情况下暂停播放,而视频在应用程序中播放,但它并没有停止。所以我通过应用代码尝试了onReceive方法,但它没有工作,所以我不知道原因。
在Android Java www.example.com中MainActivity.java,如果通过onReceive方法电源键事件关闭,应用进程屏幕会反弹。我在AndroidManifest.xml中使用了WAKE_LOCK来避免反弹,但效果不好。help.

gojuced7

gojuced71#

IntentFilter powerButtonOffFilter = new IntentFilter();
powerButtonOffFilter.addAction(Intent.ACTION_SCREEN_OFF);
powerButtonOffFilter.addAction(Intent.ACTION_SCREEN_ON);
registerReceiver(powerButtonOnOffReciever, powerButtonOffFilter);

在您的代码中,您使用了相同的Intent过滤器,它只监听操作屏幕打开,因为它会取代屏幕关闭,因为您的代码逻辑。当您想要使用单个Intent过滤器收听多个广播时,您必须将它们分组然后收听。

相关问题