3

2.1 バージョンの Android アプリケーションを作成しました。2.2 以上の更新バージョンでアプリケーションを起動すると、カメラが強制終了エラーを表示したり、カメラは起動しているのにハングしたりします。私のコードは与えられます

public class CameraCapture extends MenuActivitySpecific {

    protected ImageView image;
    protected String _path;
    File sdImageMainDirectory;
    private static final int IMAGE_CAPTURE = 0;
    private static final int GALLERY_REQUEST = 1;
    protected boolean _taken = true;
    private Uri imageUri;
    protected static final String PHOTO_TAKEN = "photo_taken";

    private Dialog dialog;
    private Handler imageUploadhandler, databaseHandler;
    DBAdapter db;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.cameracapturedimage);
        setLanguage(CameraCapture.this,"ja_JP");
        db = new DBAdapter(this);
        startCameraActivity2();
        imageUploadhandler = new Handler();
        databaseHandler = new Handler();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menucapturedimage, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.backToHome:
            finish();
            return true;
        case R.id.save:
            upload();
            return true;
        case R.id.retakePicture:
            startCameraActivity2();
            return true;

        default:
            return super.onOptionsItemSelected(item);
        }
    }

    public static void setLanguage(Context context, String languageToLoad) {
        Log.d("Message 1 ", "setting language");
        Locale locale = new Locale(languageToLoad); //e.g "sv"

        Locale.setDefault(locale);
        android.content.res.Configuration config = new android.content.res.Configuration();
        config.locale = locale;
        context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
        Log.d("Message 3: ", locale+" Language set");
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {


        try{
        if (requestCode == IMAGE_CAPTURE) {
            if (resultCode == RESULT_OK) {
                Log.d("ANDRO_CAMERA", "Picture taken!!!");
                ImageView image = (ImageView) findViewById(R.id.cameraImage);
                image.setImageURI(imageUri);
            }
            if (resultCode == RESULT_CANCELED) {
                Intent intent = new Intent(CameraCapture.this, Home.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                finish();
                startActivity(intent);
            }
        } else if (requestCode == GALLERY_REQUEST) {
            if (resultCode == RESULT_OK) {

                imageUri = data.getData();
                String selectedImagePath = getPath(imageUri);
                ImageView image = (ImageView) findViewById(R.id.cameraImage);
                image.setImageURI(imageUri);

            }
            if (resultCode == RESULT_CANCELED) {
                Intent intent = new Intent(CameraCapture.this, Home.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                finish();
                startActivity(intent);

            }
        }
        }
        catch(Exception e)
        {
            Log.e("Error: 169 CameraCapture: ", e+" ");
        }
    }

    protected void startCameraActivity2() {

        try {

            if (Constants.fromGallery) {
                Intent intent = new Intent();
                intent.setType("image/*");

                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(
                        Intent.createChooser(intent, "Select Picture"),
                        GALLERY_REQUEST);
            } else {
                Log.d("ANDRO_CAMERA", "Starting camera on the phone...");
                String fileName = "testphoto.jpg";
                ContentValues values = new ContentValues();
                values.put(MediaColumns.TITLE, fileName);
                values.put(ImageColumns.DESCRIPTION,
                        "Image capture by camera");
                values.put(MediaColumns.MIME_TYPE, "image/jpeg");
                imageUri = getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                startActivityForResult(intent, IMAGE_CAPTURE);
            }
        } catch (Exception e) {
            Log.e("Error: 174 CameraCapture: ", e + "");

        }

    }

    public String getPath(Uri uri) {
        try{
        String[] projection = { MediaColumns.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaColumns.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
        }
        catch(Exception e)
        {

            Log.e("Error: 219 CameraCapture: ", e+"");
            return null;
        }
    }

    public void upload() {
        try {
            boolean check = Utility.isNetworkAvailable(CameraCapture.this);
            // boolean check1 =isOnline();
            if (check) {


                String abc = imageUri.toString();

                Log.e("Image URI String ", abc);

                String newtime = Utility.getdate();
                String accesskey = Utility.MD5_Hash(Constants.email + newtime
                        + "moko");
                Constants.ACCESS_KEY = accesskey;
                Constants.proc_date = newtime;
                imageUploadhandler.postDelayed(runImageUpload, 500);
                dialog = ProgressDialog.show(CameraCapture.this, "",
                        "しばらくお待ちください", true);
                dialog.setCancelable(true);
            } else {

                databaseHandler.postDelayed(runDatabaseImageSave, 500);
                dialog = ProgressDialog.show(CameraCapture.this, "",
                        "しばらくお待ちください", true);
                dialog.setCancelable(true);

            }
        } catch (Exception e) {

            dialog.cancel();
            Toast.makeText(this, e + "", Toast.LENGTH_LONG).show();
        }
    }

    public byte[] getBytes(InputStream inputStream) throws IOException {

        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }
        return byteBuffer.toByteArray();
    }



    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState.getBoolean(CameraCapture.PHOTO_TAKEN)) {
            _taken = true;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean(CameraCapture.PHOTO_TAKEN, _taken);
    }

    public static void StoreImage(Context mContext, Uri imageLoc, File imageDir) {
        Bitmap bm = null;
        try {

            bm = MediaStore.Images.Media.getBitmap(
                    mContext.getContentResolver(), imageLoc);
            FileOutputStream out = new FileOutputStream(imageDir);
            bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
            Log.e("file dir", imageDir.toString());

            bm.recycle();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private final Runnable runImageUpload = new Runnable() {

        public void run() {

            ResponseFromServer response = Utility.upload(imageUri,
                    CameraCapture.this);

            if (dialog.isShowing()) {
                dialog.dismiss();
            }

            Log.i("Image Uploading status:", response.getStatus()+"");
            if (response != null) {


                if (response.getStatus().equalsIgnoreCase("OK")) {

                    Toast.makeText(getApplicationContext(), "画像を保存しました。",
                            Toast.LENGTH_LONG).show();
                    finish();
                    Intent intent=new Intent(CameraCapture.this,AllProductActivityNew.class);
                    startActivity(intent);

                }
            } else {
                new AlertDialog.Builder(CameraCapture.this)
                        .setTitle("エラー")
                        .setMessage("ファイル送信に失敗しました。")
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int which) {
                                        // TODO Auto-generated method stub
                                    }
                                }).show();
                return;

            }

        }
    };

    private final Runnable runDatabaseImageSave = new Runnable() {

        public void run() {

            try {
                InputStream iStream = getContentResolver().openInputStream(
                        imageUri);

                byte[] inputData = getBytes(iStream);
                db.open();
                String stringUri = imageUri.toString();
                String userMail = Constants.email;
                Log.e("Email: ", userMail + "");
                boolean feedback = db.InsertImage(inputData, stringUri,
                        userMail, 1);

                db.close();

                if (dialog.isShowing()) {
                    dialog.dismiss();
                }

                if (feedback) {
                    Toast.makeText(CameraCapture.this, "画像を保存しました。",
                            Toast.LENGTH_LONG).show();
                    finish();
                } else {
                    new AlertDialog.Builder(CameraCapture.this)
                            .setTitle("エラー")
                            .setMessage("ファイル送信に失敗しました。")
                            .setPositiveButton("OK",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {
                                            // TODO Auto-generated method stub
                                        }
                                    }).show();
                    return;

                }
            } catch (Exception e) {
                Log.e("Error to upload Image to database: ", e + "");
            }

        }
    };

    private boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()) {
            return true;
        }
        return false;
    }

}
4

0 に答える 0