audioManager.isMusicActive的监听器

时间:2018-05-20 07:06:06

标签: android android-audiomanager

当其他应用播放的音乐播放时,我该如何收听?

我的代码是:

if (audioManager.isMusicActive()) {
        musicontrolIcon.setImageResource(R.drawable.ic_pause_circle);
        musicontrolIcon.setOnClickListener(pauseMusic);
    } else {
        musicontrolIcon.setImageResource(R.drawable.ic_play_circle);
        musicontrolIcon.setOnClickListener(playMusic);
    }

但它只检查一次。

1 个答案:

答案 0 :(得分:0)

尝试使用JobScheduler,安排每5秒检查一次isMusicActive()的作业(或根据您的要求)。 以下是如何做到的: -

import android.app.job.JobParameters;
import android.app.job.JobService;
import android.util.Log;

public class JobSchedulerService extends JobService {
    private static final String TAG = "JobSchedulerService";
    @Override
    public boolean onStartJob(JobParameters params) {
        Log.i(TAG, "onStartJob:");
        return false;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        Log.i(TAG, "onStopJob:");
        return false;
    }

}

<强> AndroidManifest

<service android:name=".JobSchedulerService"
         android:permission="android.permission.BIND_JOB_SERVICE"
         android:exported="true"/>

创建计划程序对象

import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    JobScheduler mJobScheduler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.i(TAG, "onCreate: ");

        mJobScheduler = (JobScheduler)
                getSystemService(Context.JOB_SCHEDULER_SERVICE);
        JobInfo.Builder builder = new JobInfo.Builder(1,
                new ComponentName(getPackageName(),
                        JobSchedulerService.class.getName()));
        builder.setPeriodic(3000);
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);

        if (mJobScheduler.schedule(builder.build()) <= 0) {
            Log.e(TAG, "onCreate: Some error while scheduling the job");
        }

    }
}