如何从 Activity 调用一个类

Posted

技术标签:

【中文标题】如何从 Activity 调用一个类【英文标题】:How to call a class from Activity 【发布时间】:2014-02-12 02:31:28 【问题描述】:

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

这就是我调用相机类的方式

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;
    


【问题讨论】:

在此处检查接受的答案:***.com/questions/5991319/… 【参考方案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

【讨论】:

感谢您的回复。我尝试在 capture_image 活动中捕获图像代码。它的工作。但是我想把这2个分开。怎么做? @SajithaRathnayake 如果您愿意,您可以在不同的活动中使用它,但使用 startActivityForresult 并使用意图将路径传递回之前的活动。使用路径显示图片 如何使用 dialog.setMessage("上传文件"+ textFile);查看当前上传的文件?我试过了,但是出错了。 @SajithaRathnayake 是什么错误?如果您有完全不同的问题,请提出新问题 错误是“只有创建视图层次结构的原始线程才能接触它的视图。”【参考方案2】:

使用意图开始新课程。

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

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

确保它在您的清单文件中声明。

【讨论】:

请指导我将这些代码放在哪里。请用我的代码给我看

以上是关于如何从 Activity 调用一个类的主要内容,如果未能解决你的问题,请参考以下文章

Kotlin 类的调用方法

如何从android中的非Activity类调用服务方法

如何从另一个类(它扩展了 Activity)方法,Android 调用 CCColorLayer 类的方法?

activity的理解

从另一个方法ActionController :: UnknownFormat调用时,部分渲染不起作用

新建一个类并绑定一个activity