Android Handle和线程的使用示例

1.Handler的使用

  • 目标
    在同一个activity内实现消息的传递,接收广播后使用Handler发送消息。
  • 实现
 	//USBCameraActivity.java
 	//Handler 的实现
     private Handler handler = new Handler(){
        @Override
        public void dispatchMessage(Message msg) {
            //super.dispatchMessage(msg);
            int what = msg.what;
            switch (what){
                case 0:
                    //android 6.0之后引入的动态权限申请
                    verifyStoragePermissions(USBCameraActivity.this);
                    // 线程要做的事情
                    //Thread t.start();     
            }
        }
    };
  • 使用
/*
//此处代码为启动activity,并且架构param参数设置为cameraState_CAPTURE
Intent intent_usbcamera = new Intent(getBaseContext(),USBCameraActivity.class);
intent_usbcamera.putExtra("param",cameraState_CAPTURE);
//在service中启动activity时,需要setflags
intent_usbcamera.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(intent_usbcamera);
*/
	//USBCameraActivity.java
	//activity被激活后,该intent所带的参数
	int state = getIntent().getIntExtra("param", -1);
	//使用handler将state发送出去
	mHandler.sendEmptyMessageDelayed(state, 3000);

2 线程的使用

  • 目标
    在该activity或service中执行推流,写入文件等耗时操作时。使用Thread以避免主线程阻塞。
  • 实现和使用
    由于在线程中使用activity声明的变量,变量只能被修饰为final。所以,在这里我将使用Queue结构。
//Queue 结构体声明
private Queue<PushStructor> pushStructors = new LinkedList<>();
    public class PushStructor {
        String picPath;
        String picname;
    }
//队列锁
private Lock pushStructorslock = new ReentrantLock();
/*队列锁的使用demo
PushStructor pushStructor = new PushStructor();
pushStructor.picname = DeviceInfo.getDeviceId(DeviceInfo.PRODUCT_ID) + "_" + AppUtil.getCurrTime();
pushStructor.picPath = qiniuNeedPush;
pushStructorslock.lock();
pushStructors.offer(pushStructor);
pushStructorslock.unlock();
//MSG_CAPTURE = 0;
mHandler.sendEmptyMessage(MSG_CAPTURE); 
*/




//接上面的case 0:
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);
                    }

                    //5 为拍照次数catpturetimes确定
                    if (count == 5) {
                        isCaptureStart = false;
                        break;

                    }
                } else {

                }

            }
        }
    }).start();

3.broadcast的使用

  • 目标
    service发送一个摄像头启动的broadcast,被activity接收处理。
  • 实现
//service.java
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);
}

//Activity.java
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();
	}
	//要在onCreate中注册broadCastReceiver
	private void register() {
        IntentFilter intentFilter = new IntentFilter(); 
        intentFilter.addAction(Constants.CAPATURE_INTENT_INER); //拍照指令
        registerReceiver(mReceiver, intentFilter);
    }
    //在onDestroy中解除注册
    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, "收到语音开启摄像头推流广播");

            }
            
        }
    };
}


你可能感兴趣的:(Android Handle和线程的使用示例)