在Android

时间:2018-10-13 11:47:29

标签: android user-interface

我想开发一个应用程序,单击按钮将更改UI中的某些内容。 同时,使用前置摄像头在后台捕获照片并将图像保存在存储中。这使UI变慢。如何改善呢?

这是按钮单击侦听器。

isLikedImageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (isLiked[0])
            {
                isLiked[0] = false;
                isLikedImageButton.setImageResource(R.drawable.like_unpessed);
                isLikedTextView.setText("You have not liked this post yet");
            }
            else
            {
                isLiked[0] = true;
                isLikedImageButton.setImageResource(R.drawable.like_pressed);
                isLikedTextView.setText("You have liked this post");
                final String imageName = postNo[0]+"_"+count[0];
                Intent serviceIntent = new Intent(PostActivity.this, PhotoTakingService.class);
                serviceIntent.putExtra("imageName", imageName);
                count[0]++;
                PostActivity.this.startService(serviceIntent);
                stopService(new Intent(PostActivity.this, PhotoTakingService.class));


            }
        }
    });

这是拍照和保存代码。

public class PhotoTakingService extends Service {
String imageName;
@Override
public void onCreate() {
    super.onCreate();
    takePhoto(this);
}

@Override
public int onStartCommand (Intent intent, int flags, int startId) {
    imageName = intent.getStringExtra("imageName");
    return START_STICKY;
}

@SuppressWarnings("deprecation")
private void takePhoto(final Context context) {
    final SurfaceView preview = new SurfaceView(context);
    SurfaceHolder holder = preview.getHolder();
    // deprecated setting, but required on Android versions prior to 3.0
    holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    holder.addCallback(new SurfaceHolder.Callback() {
        @Override
        //The preview must happen at or after this point or takePicture fails
        public void surfaceCreated(SurfaceHolder holder) {
            showMessage("Surface created");

            Camera camera = null;

            try {
                camera = Camera.open(1);
                showMessage("Opened camera");

                try {
                    camera.setPreviewDisplay(holder);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                camera.startPreview();
                showMessage("Started preview");

                camera.takePicture(null, null, new android.hardware.Camera.PictureCallback() {

                    @Override
                    public void onPictureTaken(byte[] data, Camera camera) {
                        showMessage("Took picture");

                        if (data != null)
                        {
                            Bitmap bitmapTemp = BitmapFactory.decodeByteArray(data , 0, data .length);

                            Matrix matrix = new Matrix();
                            matrix.postRotate(-90);
                            Bitmap rotatedBitmap = Bitmap.createBitmap(bitmapTemp, 0, 0, bitmapTemp.getWidth(), bitmapTemp.getHeight(),
                                    matrix, true);

                            int width = rotatedBitmap.getWidth();
                            int height = rotatedBitmap.getHeight();
                            float scaleWidth = ((float) 600) / width;
                            float scaleHeight = ((float) 800) / height;
                            Matrix matrix1 = new Matrix();
                            matrix1.postScale(scaleWidth, scaleHeight);
                            Bitmap bitmap = Bitmap.createBitmap(rotatedBitmap, 0, 0, width, height,
                                    matrix1, false);

                            if (bitmap != null)
                            {

                                File file=new File(Environment.getExternalStorageDirectory()+"/dirr");
                                if(!file.isDirectory()){
                                    file.mkdir();
                                }

                                file=new File(Environment.getExternalStorageDirectory()+"/dirr",imageName+".jpg");


                                try
                                {
                                    FileOutputStream fileOutputStream=new FileOutputStream(file);
                                    bitmap.compress(Bitmap.CompressFormat.JPEG,100, fileOutputStream);

                                    fileOutputStream.flush();
                                    fileOutputStream.close();
                                }
                                catch(IOException e){
                                    e.printStackTrace();
                                }
                                catch(Exception exception)
                                {
                                    exception.printStackTrace();
                                }
                            }
                            else
                            {
                                showMessage("Null Bitmap");
                            }
                        }
                        else
                        {
                            showMessage("Null Data");
                        }

                        camera.release();
                    }
                });
            } catch (Exception e) {
                if (camera != null)
                    camera.release();
                throw new RuntimeException(e);
            }
        }

        @Override public void surfaceDestroyed(SurfaceHolder holder) {}
        @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
    });

    WindowManager wm = (WindowManager)context
            .getSystemService(Context.WINDOW_SERVICE);
    WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            1, 1, //Must be at least 1x1
            WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
            0,
            //Don't know if this is a safe default
            PixelFormat.UNKNOWN);

    //Don't set the preview visibility to GONE or INVISIBLE
    wm.addView(preview, params);
}

private static void showMessage(String message) {
    Log.i("Camera", message);
}

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

}

1 个答案:

答案 0 :(得分:0)

服务在主线程(https://developer.android.com/guide/components/services)上运行,因此您必须在不同的线程上进行繁重的操作(onPictureTaken回调内容),我在上述代码段中看到文件I / O可能很昂贵。 AsyncTask是一个好的开始,您可以探索本机线程,处理程序等。