从活动开始新的Runnable时,MediaProjection停止

时间:2019-04-08 02:31:01

标签: android

我正在使用android.media.projection.MediaProjection的实现来获取图像,并且工作正常。但是,从myService.myRunnable.run()调用MainActivity时,回调onImageAvailable()不再被调用。其中myService是绑定到活动的前景服务,而myRunnablemyService的可运行对象成员。

public class MainActivity extends Activity {

private MyService myService;

ServiceConnection mConnection = new ServiceConnection() {

    @Override
    public void onServiceDisconnected(ComponentName name) {
        isServiceBounded = false;
        myService = null;
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        isServiceBounded = true;
        MyService.LocalBinder mLocalBinder = (MyService.LocalBinder) service;
        myService = mLocalBinder.getServerInstance();
    }
};

public class ImageAvailableListener implements ImageReader.OnImageAvailableListener {
            @Override
            public void onImageAvailable(ImageReader reader) {
                Log.d(TAG, "this is called for each new frame until the button is pressed");
           ...
}

@Override
protected void onCreate(Bundle savedInstanceState) {

button.setOnClickListener(views -> {
         myService.myRunnable.run()
    });

if (!isMyServiceRunning(MyService.class)) {
        startMyService();
        bindToMyService();
    }
}

@Override
protected void onDestroy() {
    myService.killMyRunnable();// -> myRunnable = null;
    stopMyService();
    unbindService(mConnection);
    super.onDestroy();
}

private boolean isMyServiceRunning(Class<?> serviceClass) {
    ...
    if (running) ? return true : return false;

}


}

public class MyService extends Service {

IBinder mBinder = new LocalBinder();
public MyRunnable myRunnable;

public class LocalBinder extends Binder {
    public MyService getServerInstance() {
        return MyService.this;
    }
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

@Override
public void onCreate() {
    super.onCreate();
 }

 ...
}

public class MyRunnable implements Runnable {


 private void dummyWorkload(){
     Log.d(TAG, "dummyWorkload: isWorking");
     try {
         Thread.sleep(2000);
         dummyWorkload();
     } catch (InterruptedException e) {
         e.printStackTrace();
     }
 }

@Override
public void run() {
    dummyWorkload();
  }
}

是什么原因导致此问题?

1 个答案:

答案 0 :(得分:0)

代码停止MediaProjection是因为它从myRunnable.run()调用MainThread,因此在可运行对象繁忙时冻结了UI。为了使投影继续工作,应该从单独的线程中调用它。要解决此问题,请使用extends Thread而不是implements Runnable界面,或通过以下方式调用Runnable

Thread myThread = new Thread(new myRunnable);
myThread.start();