Android性能优化汇总
1.减轻主线程的压力,提高UI的流畅度
2.可以处理多个任务,开启一个线程起到多个线程的作用(looper共享)
HandlerThread与Camera的能够Looper共享
1 相机调用优化
打开相机
预览回调(编码)
异步任务的Looper,使用的MainLooper
Handler.handleMessage的执行,一定在它的Looper线程中
onPreviewFrame的执行,在Camera所持有的Looper线程中执行
new Camera -> looper -> EventHandler.handleMessage -> onPreviewFrame
IntentService(本质:Service+HandlerThread+Intent)
startService
至少要有一个空的构造方法
优点
1.提高子线程的优先级
2.减轻主线程的压力
IntentService内部会创建一个HandlerThread,onHandleIntent在HandlerThread线程中执行
Activity中启动子线程
1.内存泄露
2.无效的更新UI
public class HandlerThreadActivity2 extends Activity implements Callback {
static final String TAG = "jason";
Camera mCamera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
byte[] buffers;
HandlerThread mHandlerThread = new HandlerThread("my_handlerthread");
Handler subHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handler_thread2);
surfaceView = (SurfaceView) findViewById(R.id.surface_view);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
}
class MyTask implements Runnable, PreviewCallback{
@Override
public void run() {
//打开相机
//子线程中打开
Log.d("jason", Thread.currentThread().getName() + "_open");
mCamera = Camera.open(CameraInfo.CAMERA_FACING_BACK);
try {
mCamera.setPreviewDisplay(surfaceHolder);
} catch (IOException e) {
e.printStackTrace();
}
Camera.Parameters parameters = mCamera.getParameters();
//设置相机参数
parameters.setPreviewSize(480, 320); //预览画面宽高
mCamera.setParameters(parameters);
//获取预览图像数据
buffers = new byte[480 * 320 * 4];
mCamera.addCallbackBuffer(buffers);
mCamera.setPreviewCallbackWithBuffer(this);
mCamera.startPreview();
Log.d(TAG, Thread.currentThread().getName()+ "_run");
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
if(mCamera != null){
mCamera.addCallbackBuffer(buffers);
//编码
Log.d(TAG, Thread.currentThread().getName()+ "_onPreviewFrame");
}
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mHandlerThread.start();
subHandler = new Handler(mHandlerThread.getLooper());
subHandler.post(new MyTask());
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
Demo: Lsn19Activity
2 Loader
Loader保证子线程与Activity或者Fragment的生命周期一致
Activity和Fragment自带LoaderManager
优点:
- 方便
- Activity或者Fragment的生命周期一致
- 数据缓存与更新通知