如何从Activity调用一个类

时间:2014-01-22 06:48:09

标签: android android-activity android-camera

我是Android开发新手,开发的程序可以从Camera中捕获图像并存储在SD卡中。问题是我单独创建Camera类并尝试调用capture_image Activity。这是我的代码。请帮我解决这个问题。

这就是我调用Camera class

的方式
Camera cam=new Camera();
fileUri= cam.captureImage();

这是capture_image活动

package com.example.imagecapture;

import java.io.File;
import java.io.FileOutputStream;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.Toast;




public class capture_image extends Activity {




    private Uri fileUri; 
    private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
    private static int RESULT_LOAD_IMAGE = 1;

    private ImageView image1;
    private ImageView image2;
    private ImageView image3;
    private ImageView image4;
    private ImageView image5;
    private ImageView image6;
    private ImageView image7;
    private ImageView image8;

    //private LocationManager locationManager;
    private ImageView[] IMGS = { image1, image2, image3,image4,image5,image6,image7,image8 };
    private File file;

    private String[] FileNameStrings = new String[8];

    private File[] listFile;



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



        setContentView(R.layout.capture_details);

        Button buttonLoadImage = (Button) findViewById(R.id.btnBrowseimage);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });

        Button buttonLoadCamera = (Button) findViewById(R.id.btnCapture);
        buttonLoadCamera.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // capture picture
                try
                {
                    Camera cam=new Camera();
                    fileUri= cam.captureImage();

                 } catch (NullPointerException e) {
                     e.printStackTrace();
                     //Toast.makeText(getBaseContext(), "Error:1 on uplod file", Toast.LENGTH_LONG).show();

                 } catch (Exception e) {
                     e.printStackTrace();
                     //Toast.makeText(getBaseContext(), "Error:2 File may be already exists", Toast.LENGTH_LONG).show();

                 } 





            }
        });


        Button buttonSendData = (Button) findViewById(R.id.btnSend);
        buttonSendData.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                new PostDataAsyncTask().execute();
            }
        });

        Button buttonCancel = (Button) findViewById(R.id.btnCancel);
        buttonCancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                finish();
                System.exit(0);
            }
        });





        /**
         * Checking GPS
         * */
        //locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //Toast.makeText(getBaseContext(), "Gps turned on ", Toast.LENGTH_LONG).show();
        /**/

        //TelephonyManager mTelephonyMgr;
        //mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 

        //String myPhoneNumber = mTelephonyMgr.getLine1Number();
        //myPhoneNumber.substring(2);

    }

    /**
     * Checking GPS
     * */
    public void onLocationChanged(Location location) {

        String str = "Latitude: "+location.getLatitude()+" Longitude: "+location.getLongitude();

        Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
    }

    public void onProviderDisabled(String provider) {
        Toast.makeText(getBaseContext(), "Gps turned off ", Toast.LENGTH_LONG).show();
    }

    public void onProviderEnabled(String provider) {
        Toast.makeText(getBaseContext(), "Gps turned on ", Toast.LENGTH_LONG).show();
    }
    /**/









    /**
     * Display image from a path to ImageView
     */
    @SuppressLint("SdCardPath")
    private void previewCapturedImage() {
        try {

             // bimatp factory
            BitmapFactory.Options options = new BitmapFactory.Options();

            // downsizing image as it throws OutOfMemory Exception for larger
            options.inSampleSize = 8;

            final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);


            //Saving captured image to sdcard/cers
            String filaname=  Get_next_file_name();
            try {
                FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory() + File.separator  + "cers"+ File.separator+ filaname+".jpg");
                bitmap.compress(Bitmap.CompressFormat.PNG, 80, out);
                out.close();
             } catch (Exception e) {
                    e.printStackTrace();
             }


            //imgPreview.setImageBitmap(bitmap);
            IMGS[0] = (ImageView) findViewById(R.id.imageViewphoto1);
            IMGS[1] = (ImageView) findViewById(R.id.imageViewphoto2);
            IMGS[2] = (ImageView) findViewById(R.id.imageViewphoto3);
            IMGS[3] = (ImageView) findViewById(R.id.imageViewphoto4);
            IMGS[4] = (ImageView) findViewById(R.id.imageViewphoto5);
            IMGS[5] = (ImageView) findViewById(R.id.imageViewphoto6);
            IMGS[6] = (ImageView) findViewById(R.id.imageViewphoto7);
            IMGS[7] = (ImageView) findViewById(R.id.imageViewphoto8);


            for(int i=0;i<8;i++)
            {
                 if((String) IMGS[i].getTag()==null)
                 {
                    IMGS[i].setImageBitmap(bitmap);
                    File finalFile = new File(Environment.getExternalStorageDirectory() + File.separator  + "cers"+ File.separator+ filaname+".jpg");

                    FileNameStrings[i]= new String(finalFile.getAbsolutePath().toString());
                    IMGS[i].setTag( "image" +i);
                    IMGS[i].getLayoutParams().height = 100;
                    IMGS[i].getLayoutParams().width = 100;

                    break;
                 }

            }


        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    public String Get_next_file_name()
    {
        int fn,ofn=0;
        String[] filename;


        // Check for SD Card
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "Error! No SDCARD Found!", Toast.LENGTH_LONG).show();
        } else {
            // Locate the image folder in your SD Card
            file = new File(Environment.getExternalStorageDirectory()  + File.separator +"cers");
            // Create a new folder if no folder named SDImageTutorial exist
            file.mkdirs();
        }

        if (file.isDirectory()) {
            listFile = file.listFiles();

            for (int i = 0; i < listFile.length; i++) {

                filename =listFile[i].getName().split(".");

                try
                {
                    fn=Integer.parseInt(filename[0]);
                    if(ofn<fn)
                    {
                        ofn=fn;
                    }

                    ofn=ofn+1;
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
            }
        }

        StringBuilder sb = new StringBuilder();
        sb.append("");
        sb.append(ofn);

        return  sb.toString();
    }








    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // if the result is capturing Image
        if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // successfully captured the image
                // display it in image view
                previewCapturedImage();
            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled Image capture
                Toast.makeText(getApplicationContext(),
                        "User cancelled image capture", Toast.LENGTH_SHORT)
                        .show();
            } else {
                // failed to capture image
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                        .show();
            }
        } 

        // Browse Images
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();


            IMGS[0] = (ImageView) findViewById(R.id.imageViewphoto1);
            IMGS[1] = (ImageView) findViewById(R.id.imageViewphoto2);
            IMGS[2] = (ImageView) findViewById(R.id.imageViewphoto3);
            IMGS[3] = (ImageView) findViewById(R.id.imageViewphoto4);
            IMGS[4] = (ImageView) findViewById(R.id.imageViewphoto5);
            IMGS[5] = (ImageView) findViewById(R.id.imageViewphoto6);
            IMGS[6] = (ImageView) findViewById(R.id.imageViewphoto7);
            IMGS[7] = (ImageView) findViewById(R.id.imageViewphoto8);


            for(int i=0;i<8;i++)
            {
                 if((String) IMGS[i].getTag()==null)
                 {
                    //IMGS[i].setImageBitmap(decodeSampledBitmapFromResource(getResources(), R.id.tempimage, 100, 100));
                    IMGS[i].setImageBitmap(BitmapFactory.decodeFile(picturePath));

                    File finalFile = new File(picturePath);

                    FileNameStrings[i]= new String(finalFile.getAbsolutePath().toString());

                    IMGS[i].setTag( "image" +i);
                    IMGS[i].getLayoutParams().height = 100;
                    IMGS[i].getLayoutParams().width = 100;
                    IMGS[i].setScaleType(ScaleType.FIT_CENTER);
                    break;
                 }
            }


        }


    }
}

此处出现错误(相机类)

// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);

这是相机类

package com.example.imagecapture;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;


public class Camera  extends Activity{

    private Uri fileUri;
    private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
    private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;
    private static final String IMAGE_DIRECTORY_NAME = "CERS";
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }


    public boolean DeviceSupportCamera()
    {
        if (!isDeviceSupportCamera()) {
            return false;
        }
        else
        {
            return true;
        }
    }

     /**
     * Checking device has camera hardware or not
     * */
    public  boolean isDeviceSupportCamera() {
        if (getApplicationContext().getPackageManager().hasSystemFeature(
            PackageManager.FEATURE_CAMERA)) {
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }

    /**
     * Capturing Camera Image will lauch camera app requrest image capture
     */
    public Uri captureImage() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

        // start the image capture Intent
        startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);

        return fileUri;
    }

    /**
     * Here we store the file url as it will be null after returning from camera
     * app
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // save file url in bundle as it will be null on scren orientation
        // changes
        outState.putParcelable("file_uri", fileUri);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        // get the file url
        fileUri = savedInstanceState.getParcelable("file_uri");
    }



    /**
     * ------------ Helper Methods ---------------------- 
     * */

    /**
     * Creating file uri to store image
     */
    public Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    /**
     * returning image / video
     */
    private static File getOutputMediaFile(int type) {

        // External sdcard location
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                IMAGE_DIRECTORY_NAME);

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
                        + IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "IMG_" + timeStamp + ".jpg");
        } 
        else if (type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "VID_" + timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }

}

2 个答案:

答案 0 :(得分:1)

您永远不应该创建Activity类的实例。检查Raghav Sood的答案

Can i Create the object of a activity in other class?

Camera cam=new Camera();

你有

public class Camera  extends Activity{

活动在清单中声明并具有生命周期。而是使用startActivitystartActivityForResult

此外,您不需要

 public static void main(String[] args) {
    // TODO Auto-generated method stub

}

将捕获图像代码移至capture_image并使用startActivityForResult

答案 1 :(得分:1)

使用意图开始新课程。

Intent i = new Intent(capture_image.this, Camera.class);
startActivity(i);

OR

startActivityForResult(i); // if you need to get back a result from Camera class

确保在Manifest文件中声明它。