1

很抱歉再次问同样的问题,但在寻找答案后,我没有编写正常工作的代码。

ñ这是我调用活动的主要功能:

package com.phonegap.CameraPluginTest;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.phonegap.DroidGap;

public class CameraPluginTest2_3Activity extends DroidGap {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        super.loadUrl("file:///android_asset/www/index.html");
        try{
            CustomCamera camera = new CustomCamera(this);
            appView.addJavascriptInterface(camera, "CustomCamera");
            //camera.Cameratest();
            //camera.startCamera(50);
        }catch(Exception ex){
            ex.printStackTrace();
            Log.e("RapportsError",  "error" + ex.toString());
        }
    }

    public class CustomCamera{
        private Context context;

        public CustomCamera (Context context){
            this.context = context;

        }

        public void Cameratest() {
            Log.e("RapportsError",  "Cameratest");

        }
        public void startCamera(int quality)
        {
            Log.e("RapportsError",  "intent");
            try{

                Intent i = new Intent(context, CameraPreview.class);

                i.setAction("android.intent.action.PICK");
                i.putExtra("quality", quality);
                startActivityForResult(i, 1);
                Log.e("RapportsError",  "despues de intent" );
            }catch(Exception ex){
                ex.printStackTrace();
                Log.e("RapportsError",  "error" + ex.toString());
            }
        }

        protected void onActivityResult(int reqCode, int resCode, Intent intent)
        {
            String data;            
            Log.e("RapportsError",  "ON ACTIVITY RESULT " + reqCode);
            //super.onActivityResult(requestCode, resultCode, intent);
            if (resCode == RESULT_OK)
            {
                data = intent.getStringExtra("picture"); 
                Log.e("RapportsError",  "error" + data);
                // Send the graphic back to the class that needs it
                //launcher.processPicture(data);
            }
            else
            {
                //launcher.failPicture("Did not complete!");
            }
        }

    }

}

这是被调用的类

package com.phonegap.CameraPluginTest;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import java.io.IOException;
import java.util.List;

import org.apache.commons.codec.binary.Base64;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import android.graphics.YuvImage;
import android.os.Environment;

public class CameraPreview extends Activity implements SurfaceHolder.Callback{

    private static final String TAG = "PhoneGapCamera";
    private SurfaceView mSurfaceView;
    private SurfaceHolder mSurfaceHolder;

    private RelativeLayout root;

    Camera mCamera;
    boolean mPreviewRunning = false;

    int quality;
    Intent mIntent;

    public void onCreate(Bundle icicle)
    {
        super.onCreate(icicle);

        Log.e(TAG, "onCreate");

        getWindow().setFormat(PixelFormat.TRANSLUCENT);

        RelativeLayout.LayoutParams containerParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, 
                ViewGroup.LayoutParams.FILL_PARENT);
        LinearLayout.LayoutParams surfaceParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, 
                ViewGroup.LayoutParams.FILL_PARENT, 0.0F);
        RelativeLayout.LayoutParams buttonParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 
                ViewGroup.LayoutParams.WRAP_CONTENT);

        root = new RelativeLayout(this);
        root.setLayoutParams(containerParams);

        mSurfaceView = new SurfaceView(this);
        mSurfaceView.setLayoutParams(surfaceParams);
        root.addView(mSurfaceView);

        Button stopButton = new Button(this);
        stopButton.setText("click");
        buttonParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        buttonParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        buttonParams.rightMargin = 5;
        buttonParams.topMargin = 5;

        stopButton.setLayoutParams(buttonParams);
        root.addView(stopButton);

        setContentView(root);

        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.addCallback(this);
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);                    
        mIntent = this.getIntent();

        quality = mIntent.getIntExtra("quality", 100);


        stopButton.setOnClickListener(mSnapListener);
    }

    private OnClickListener mSnapListener = new OnClickListener() {
        public void onClick(View v) {
            mCamera.takePicture(null, null, mPictureCallback);
        }
    };

    //public boolean onCreateOptionsMenu(android.view.Menu menu) {
    //    MenuItem item = menu.add(0, 0, 0, "goto gallery");
    //    item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
    //        public boolean onMenuItemClick(MenuItem item) {
    //            Uri target = Uri.parse("content://media/external/images/media");
    //            Intent intent = new Intent(Intent.ACTION_VIEW, target);
    //            startActivity(intent);
    //            return true;
    //        }
    //    });
    //    return true;
    //}

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

    /*
     * We got the data, send it back to PhoneGap to be handled and processed.
     * 
     */

   // Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
   //     public void onPictureTaken(byte[] data, Camera c) {
   //         Log.e(TAG, "PICTURE CALLBACK: data.length = " + data.length);
   //         storeAndExit(data);

   //     }
    //};

    Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {        
        public void onPictureTaken(byte[] data, Camera _camera) {                        
              storeAndExit(data,_camera);
              Log.d(TAG, "onPictureTaken - jpeg");                            
        }
      };

    /*
     * We can't just store and exit, because Android freezes up when we try to cram a picture across a process in a Bundle.
     * We HAVE to compress this data and send back the compressed data  
     */
    public void storeAndExit(byte[] data,Camera _camera)
    {       
          FileOutputStream outStream = null;          
          String fotoName = new String();
          try {
          fotoName="wy"+System.currentTimeMillis();
          outStream = new FileOutputStream(String.format(
                  "/sdcard/%s.png", fotoName));
          outStream.write(data);
          outStream.close();
          Log.e(TAG, "PICTURE CALLBACK: fotoName" + fotoName + "data.length = " + data.length);
          String js_out = new String( "/sdcard/" + fotoName + ".png");

          mIntent.putExtra("picture", js_out);
              //setResult(RESULT_OK, mIntent);
          this.setResult(RESULT_OK, mIntent);
         // Uri imageUri = Uri.fromFile(outStream);
         // storeAndExit(data);
              finish();
          } catch (FileNotFoundException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          } finally {
          }           
    }

    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK) {         
            return super.onKeyDown(keyCode, event);
        }

        if (keyCode == KeyEvent.KEYCODE_CAMERA || keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_SEARCH) {
            mCamera.takePicture(null, null, mPictureCallback);
            return true;
        }

        return false;
    }

    protected void onResume()
    {
        Log.e(TAG, "onResume");
        super.onResume();
    }

    protected void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
    }

    protected void onStop()
    {
        Log.e(TAG, "onStop");
        super.onStop();
    }

    public void surfaceCreated(SurfaceHolder holder)
    {
        Log.e(TAG, "surfaceCreated");
        mCamera = Camera.open();
        //mCamera.startPreview();
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h)
    {
        Log.e(TAG, "surfaceChanged");

        // XXX stopPreview() will crash if preview is not running
        if (mPreviewRunning) {
            mCamera.stopPreview();
        }

        Camera.Parameters p = mCamera.getParameters();
        List<Camera.Size> previewSizes = p.getSupportedPreviewSizes();

        Camera.Size previewSize = previewSizes.get(0);


        p.setPreviewSize(previewSize.width, previewSize.height);
        mCamera.setParameters(p);
        try {
            mCamera.setPreviewDisplay(holder);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mCamera.startPreview();
        mPreviewRunning = true;
    }

    public void surfaceDestroyed(SurfaceHolder holder)
    {
        Log.e(TAG, "surfaceDestroyed");
        mCamera.stopPreview();
        mPreviewRunning = false;
        mCamera.release();
    }

    public void onPreviewFrame(byte[] data, Camera camera) {
        try {
            Camera.Parameters parameters = camera.getParameters();
            Size size = parameters.getPreviewSize();
            YuvImage image = new YuvImage(data, parameters.getPreviewFormat(),
                    size.width, size.height, null);
            File file = new File(Environment.getExternalStorageDirectory()
                    .getPath() + "/out.jpg");
            FileOutputStream filecon = new FileOutputStream(file);
            image.compressToJpeg(
                    new Rect(0, 0, image.getWidth(), image.getHeight()), 90,
                    filecon);
        } catch (FileNotFoundException e) {
            Toast toast = Toast
                    .makeText(getBaseContext(), e.getMessage(), 1000);
            toast.show();
        }
    }


}

这是清单

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.phonegap.CameraPluginTest"
    android:versionCode="1"
    android:versionName="1.0" >

<supports-screens 
    android:largeScreens="true" 
    android:normalScreens="true" 
    android:smallScreens="true" 
    android:resizeable="true" 
    android:anyDensity="true" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:debuggable="true" >
        <activity
            android:name=".CameraPluginTest2_3Activity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".CameraPreview" 
            android:label="CameraPreviewLabel" 
            android:configChanges="orientation|keyboardHidden"
            android:screenOrientation="landscape">
        </activity>                
    </application>

</manifest>

主要问题是我可以拍照,所以对课程的调用正在工作,但没有调用 onActivityResult。

你有线索吗?

非常感谢,很抱歉再次提出同样的问题,但我不明白问题出在哪里。

问候

4

4 回答 4

4

看到你对你的问题的回答。你可以让你的活动回到你的插件的方法是确保:

this.cordova.setActivityResultCallback(MyActivity.this);

在您执行 startActivityForResult()... 调用之前调用。真正困扰我的事情似乎没有人在任何地方回答。必须自己找出来。

顺丰

于 2013-01-08T16:43:37.897 回答
1

如果您的主 Activity 中有 onActivityResult(),则必须确保它调用其父级的方法以正确处理插件:

public class MainActivity extends CordovaActivity {
                    //or 'extends DroidGap' based on Cordova version

    //...

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
            if (requestCode == MyCustomActivity) {
                    doMyCustomActivity(requestCode);
            }
            else { //call onActivityResult() of the plugins
                super.onActivityResult(requestCode, resultCode, intent);
            }
    }

    //...
}
于 2015-02-18T10:24:39.940 回答
0

在我更改 AndroidManifest.xml 中的 launchMode 之前,我无法让 onActivityResult 工作

这个不工作

android:launchMode="singleInstance"

standardsingleTop对我来说很好用。

我看到您的清单中没有launchMode,所以我不确定它会对您的情况有所帮助。但我希望它可以帮助其他人解决这个问题。

于 2013-04-08T21:19:58.913 回答
0

好的,我建议您更改您的类 CustomCamera 以扩展 PhoneGap 提供的插件接口。我们处理原生层和 JavaScript 层之间通信的所有小问题。使用 addJavascriptInterface 时会弹出一些问题,您必须解决这些问题,包括显示的键盘会重新加载您的应用程序、界面在某些版本的模拟器上不起作用等。只需使用我们的插件 API 即可对你来说更容易。

如何为 Android 创建插件

查看PhoneGap 中相机代码的 src,因为我们刚刚为 Android 启动了拍照意图,您可以使用相同的方法,但改为启动您的意图。

于 2012-06-06T13:44:42.813 回答