我正在使用android.media.projection.MediaProjection
的实现来获取图像,并且工作正常。但是,从myService.myRunnable.run()
调用MainActivity
时,回调onImageAvailable()
不再被调用。其中myService
是绑定到活动的前景服务,而myRunnable
是myService
的可运行对象成员。
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();
}
}
是什么原因导致此问题?
答案 0 :(得分:0)
代码停止MediaProjection
是因为它从myRunnable.run()
调用MainThread
,因此在可运行对象繁忙时冻结了UI。为了使投影继续工作,应该从单独的线程中调用它。要解决此问题,请使用extends Thread
而不是implements Runnable
界面,或通过以下方式调用Runnable
:
Thread myThread = new Thread(new myRunnable);
myThread.start();