无法在onCreate中创建相机预览



我在Android上预览相机时遇到了一些问题。

现在我有一个按钮,你需要按下,然后才能预览相机。但我希望你一启动应用程序就可以预览。

如果我试图将启动预览的部分从按钮中取出,并将其放入onCreate,它不会工作,预览也不会启动。

如何在用户无需触摸按钮的情况下创建预览?

此外,我有一个HTC Desire高清,预览是转90度为我。为什么会发生这种情况?

Camera cam;
SurfaceView surf;
SurfaceHolder holder;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button btnStart= (Button)findViewById(R.id.startCamPrev);
    getWindow().setFormat(PixelFormat.UNKNOWN);
    surf = (SurfaceView)findViewById(R.id.surfaceView);
    holder = surf.getHolder();
    holder.addCallback(this);
    holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    btnStart.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {
            cam = Camera.open();
            if(cam != null)
            {
                try
                {
                    cam.setPreviewDisplay(holder);
                    cam.startPreview();
                }
                catch(IOException e)
                {
                }
            }
        }
    });
}

清单文件:

     <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
         package="LSAB.CamTest"
         android:versionCode="1"
         android:versionName="1.0">
       <application android:icon="@drawable/icon" android:label="@string/app_name">
           <activity android:name=".CameraTest"
                     android:label="@string/app_name">
               <intent-filter>
                   <action android:name="android.intent.action.MAIN" />
                   <category android:name="android.intent.category.LAUNCHER" />
               </intent-filter>
           </activity>
       </application>
       <uses-sdk android:minSdkVersion="4" />
    <uses-permission android:name="android.permission.CAMERA"></uses-permission>
    </manifest>

Main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Hello World, CameraTest"
    />
<Button
    android:id = "@+id/startCamPrev"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="- Start Preview -"
    />
 <SurfaceView
     android:id="@+id/surfaceView"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     />
</LinearLayout>

除了将setPreviewDisplay添加到onCreate之外,还可以尝试执行->

实现SurfaceHolder.Callback

onSurfaceChanged方法中,使用传递给该方法的新surfaceHolder重置setPreviewDisplay

这对我有效。

您检查过清单中的权限吗?也尽量不要在OnCreate中做那么多,这是一种糟糕的做法,出于上帝的爱,如果你需要帮助,请对代码进行评论。

好的,试着改变布局的方向,然后告诉我会发生什么。

最新更新