1.Handler的使用
- 目标
在同一个activity内实现消息的传递,接收广播后使用Handler发送消息。 - 实现
private Handler handler = new Handler(){
@Override
public void dispatchMessage(Message msg) {
int what = msg.what;
switch (what){
case 0:
verifyStoragePermissions(USBCameraActivity.this);
}
}
};
int state = getIntent().getIntExtra("param", -1);
mHandler.sendEmptyMessageDelayed(state, 3000);
2 线程的使用
- 目标
在该activity或service中执行推流,写入文件等耗时操作时。使用Thread以避免主线程阻塞。 - 实现和使用
由于在线程中使用activity声明的变量,变量只能被修饰为final。所以,在这里我将使用Queue结构。
private Queue<PushStructor> pushStructors = new LinkedList<>();
public class PushStructor {
String picPath;
String picname;
}
private Lock pushStructorslock = new ReentrantLock();
case 0:
new Thread(new Runnable() {
@Override
public void run () {
int count = 0;
while (true) {
if (pushStructors.size() != 0) {
count++;
try {
Pushqiniu pushqiniu = new Pushqiniu();
PushStructor pushStructorThread;
pushStructorThread = pushStructors.poll();
Log.i(TAG, "CAPparam: picname: " + pushStructorThread.picname + "; picpath: " + pushStructorThread.picPath);
String pushFileUrl = pushqiniu.push(pushStructorThread.picPath, pushStructorThread.picname);
Log.i(TAG, "CAPpushFileUrl: " + pushFileUrl);
MyApplication.add(pushFileUrl);
Thread.sleep(1000);
} catch (Exception e) {
MyApplication.sendErrorMsg(0);
}
if (count == 5) {
isCaptureStart = false;
break;
}
} else {
}
}
}
}).start();
3.broadcast的使用
- 目标
service发送一个摄像头启动的broadcast,被activity接收处理。 - 实现
public class VoiceVControlService extends Service{
private Context mCtx;
mCtx = this;
cameraState = cameraState_recording;
intent_second = new Intent(Constants.START_VIDEO_PUSH_INTENT_INER);
mCtx.sendBroadcast(intent_second);
}
public class USBCameraActivity extends AppCompatActivity{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_usbcamera);
register();
}
@Override
protected void onDestroy() {
super.onDestroy();
unRegister();
}
private void register() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Constants.CAPATURE_INTENT_INER);
registerReceiver(mReceiver, intentFilter);
}
private void unRegister() {
unregisterReceiver(mReceiver);
}
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Constants.START_VIDEO_PUSH_INTENT_INER.equals(action)){
Log.i(TAG, "收到语音开启摄像头推流广播");
}
}
};
}