简体   繁体   English

在第二个活动中调用时,Android无法连接到摄像头服务

[英]Android fails to Connect to camera service when called in a second activity

I am writing an app which takes pictures every x-seconds, detects differences above a threshold and eventually sends high-def pictures out via email. 我正在编写一个应用程序,该应用程序每x秒拍摄一次图片,检测超过阈值的差异,并最终通过电子邮件发送高清图片。 The app workd fine if I keep all the camera functions in the same class as the main, but then the code gets messy and it also becomes more tricky to take pictures in threads. 如果我将所有相机功能都与主相机保持在同一类中,则该应用程序运行良好,但是代码变得混乱,并且在线程中拍照也变得更加棘手。 So I decided to move all the camera functions in a second java class (TakePic.java) and call this every x-seconds from the main class. 因此,我决定将所有相机功能移到第二个Java类(TakePic.java)中,并每隔x秒从主类调用一次。 For the moment it would be fine if I could at least call it once, but I can't. 目前,如果我至少可以调用一次是可以的,但是我不能。 Here is my code: 这是我的代码:

The AndroidManifest.xml AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest android:versionCode="1"
      android:versionName="1.0"
      package="com.lyo.android.CameraSender5"
      xmlns:android="http://schemas.android.com/apk/res/android">

<uses-sdk android:minSdkVersion="5"
        android:targetSdkVersion="6" />
<supports-screens android:largeScreens="false"
                android:normalScreens="true"
                android:smallScreens="false" />

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>  
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.RECEIVE_SMS" />
<uses-feature android:name="android.hardware.RECEIVE_MMS" />
<uses-feature android:name="android.hardware.read_owner_data" />
<uses-feature android:name="android.hardware.write_owner_data" />
<uses-feature android:name="android.hardware.acccess_network_state" />

<application 
  android:icon="@drawable/cw"
  android:label="@string/app_name">
<activity 
    android:configChanges="keyboardHidden|orientation"
    android:label="@string/app_name"
    android:name=".PreviewDemo"
    android:screenOrientation="landscape"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen">

  <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
  </intent-filter>
</activity>
<activity 
    android:configChanges="keyboardHidden|orientation"
    android:label="@string/app_name"
    android:name=".TakePic"
    android:screenOrientation="landscape"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen">        
  <intent-filter>
    <action android:name="com.lyo.android.TAKEPIC" />
    <category android:name="android.intent.category.DEFAULT" />
  </intent-filter>
</activity>
</application>
</manifest>

The following is the Main class: 以下是Main类:

package com.lyo.android.CameraSender5;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
//import android.hardware.Camera;
//import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
//import android.view.SurfaceHolder;
//import android.view.SurfaceView;
import android.widget.TextView;
import android.widget.Toast;


import com.lyo.android.CameraSender5.R;


public class PreviewDemo extends Activity 
{
  //private SurfaceView preview=null;
  //private SurfaceHolder previewHolder=null;
  //private Camera camera=null;
  private boolean inPreview=false;
  private boolean cameraConfigured=false;
  public static Integer fileNameINT = 1; 
  /*START*/  
  public static final int MEDIA_TYPE_IMAGE = 1;
  public Bitmap bitmapPictureOld;
  public Bitmap bitmapPictureNew;
  public int singlePixelNew;
  public int singlePixelOld;
  public int colorREDsum = 0;
  public int firstLoop = 1;
  public int tollerance = 500000; //Devi ridurre la tolleranza fino a che c'e' una image detection
  @Override
  public void onCreate(Bundle savedInstanceState) 
  {
  Log.e("onCreate", "onCreate started");
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  Log.e("onCreate", "ContentView set");
  //TakePic TakePic = new TakePic();
  Log.e("onCreate", "TakePic called");
  //TakePic.initialize(this);
  Log.e("onCreate", "Initialized");
  startActivity(new Intent("com.lyo.android.TAKEPIC"));
    //try 
    //{
//  Thread.sleep(1000);
//} 
    //catch (InterruptedException e) 
//{
//  // TODO Auto-generated catch block
//  e.printStackTrace();
//}
    //colorREDsum = 0;
  try 
  {
    Thread.sleep(3000);
  } 
  catch (InterruptedException e) 
  {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
    //this.runOnUiThread(Timer_Tick);
    //camera.takePicture(null, null, mPicture);
  }};

And this is the TakePic.java class where I have input all my camera functions (these used to be in the main class and they worked fine): 这是TakePic.java类,我在其中输入了我所有的相机功能(这些功能曾经在主类中使用,它们可以正常工作):

package com.lyo.android.CameraSender5;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.PreviewCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.TextView;
import android.widget.Toast;

import com.lyo.android.CameraSender5.R; 

public class TakePic extends Activity
{

public SurfaceView preview=null;
public SurfaceHolder previewHolder=null;
public Camera camera=null;
public boolean inPreview=false;
public boolean cameraConfigured=false;
public static Integer fileNameINT = 1;

/*START*/  
public static final int MEDIA_TYPE_IMAGE = 1;
public Bitmap bitmapPictureOld;
public Bitmap bitmapPictureNew;
public int singlePixelNew;
public int singlePixelOld;
public int colorREDsum = 0;
public int firstLoop = 1;
public int tollerance = 500000; //Devi ridurre la tolleranza fino a che c'e' una image detection


//@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (camera != null) {
    camera.stopPreview();
    camera.setPreviewCallback(null);
    camera.release();
    camera = null;
    }
}

//@Override
public void surfaceCreated(SurfaceHolder holder) {
if (camera == null) {
    camera = Camera.open();
    try {
        camera.setPreviewDisplay(holder);

        // TODO test how much setPreviewCallbackWithBuffer is faster
        camera.setPreviewCallback((PreviewCallback) this);
    } catch (IOException e) {
        camera.release();
        camera = null;
    }
    }
}


@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    //setContentView(R.layout.main);
    if (camera != null) {
        Log.e("LYO TakePic onResume", "CAMERA NOT NULL");
        camera.unlock();
        camera.stopPreview();
        camera.unlock();
        camera.setPreviewCallback(null);
        camera.unlock();
        camera.release();
        camera.unlock();
        camera = null;
    }
    else
    {
        Log.e("LYO TakePic onResume", "CAMERA NULL");
    }

    Log.e("LYO TakePic onResume", "onResume Start");
    camera = Camera.open();
    Log.e("LYO TakePic onResume", "Camera opened");
    camera.startPreview();
    startPreview();
    Log.e("LYO TakePic onResume", "Preview Started");
    colorREDsum = 0;
}


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    Log.e("LYO TakePic onCreate", "Setting content view");
    setContentView(R.layout.main);
    Log.e("LYO TakePic onCreate", "Content View Set");
    Log.e("LYO TakePic onCreate", "Initialization started");
    preview=(SurfaceView)this.findViewById(R.id.preview);
    Log.e("LYO TakePic onCreate", "preview set");
    previewHolder=preview.getHolder();
    previewHolder.addCallback(surfaceCallback);
    previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    Log.e("LYO TakePic onCreate", "holder set");
    colorREDsum = 0;
}


private PictureCallback mPicture = new PictureCallback() 
  {

        //@Override
        public void onPictureTaken(byte[] data, Camera camera) 
        {
            Log.e("PICTURE TAKEN", "START");
            colorREDsum = 0;
            if (firstLoop == 1)
            {
                Log.e("PICTURE TAKEN", "1st LOOP");
                bitmapPictureNew = BitmapFactory.decodeByteArray(data, 0, data.length);
                firstLoop = 0;
            } 
            else 
            {
                Log.e("PICTURE TAKEN", "OTHER LOOP");
                bitmapPictureOld = Bitmap.createBitmap(bitmapPictureNew);
                //bitmapPictureOld.createBitmap(bitmapPictureNew, 0, 0, bitmapPictureNew.getWidth(), bitmapPictureNew.getHeight());

                //Bitmap bitmapPictureOld = bitmapPictureNew;
                bitmapPictureNew = BitmapFactory.decodeByteArray(data, 0, data.length);
                colorREDsum = 0;
                int counter = 0;
                for (int height = 0; height <= bitmapPictureNew.getHeight() - 1; height++)
                {
                    for (int width = 0; width <= bitmapPictureNew.getWidth() - 1; width++)
                    {
                        singlePixelNew = bitmapPictureNew.getPixel(width, height);
                        singlePixelOld = bitmapPictureOld.getPixel(width, height);
                        colorREDsum = colorREDsum + (Color.red(singlePixelNew) - Color.red(singlePixelOld));
                        counter = counter +1;
                    }
                }

                TextView tv1 = (TextView) findViewById(R.id.integer1);
                tv1.setText(String.valueOf(colorREDsum));
                try 
                {
                    Thread.sleep(500);
                } 
                catch (InterruptedException e) 
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


                if(colorREDsum > tollerance)
                {
                    //send message
                    Log.e("PICTURE TAKEN", "RED > TOLLERANCE");
                    //TEMP
                    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmapPictureOld.compress(Bitmap.CompressFormat.PNG, 100, bytes);

                    //you can create a new file name "test.jpg" in sdcard folder.
                    File f = new File(Environment.getExternalStorageDirectory() + File.separator + "ALARM.png");

                    try 
                    {
                        f.createNewFile();
                        //write the bytes in file
                        FileOutputStream fo = new FileOutputStream(f);
                        fo.write(bytes.toByteArray());
                        fo.close();
                    } 
                    catch (IOException e1) 
                    {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                    //camera.startPreview();    

                    Log.e("PICTURE TAKEN", "START MAILING");
                    Mail m = new Mail("*****@.com", "*****");
                    String[] toArr = {"*****@hotmail.com"}; 
                    m.setTo(toArr); 
                    m.setFrom("*****@gmail.com"); 
                    m.setSubject("Ciao Ciao"); 
                    m.setBody("You never know... :)"); 

                    try
                    {
                        Log.e("PICTURE TAKEN", "START SEND TRY");
                        tv1.setText("Start Sending");
                        //try 
                        //{
                        //  Log.e("PICTURE TAKEN", "SLEEP 500");
                        //  Thread.sleep(500);
                        //} 
                        //catch (InterruptedException e) 
                        //{
                        //  // TODO Auto-generated catch block
                        //  e.printStackTrace();
                        //}
                        //START SEND
                        MimeMessage msg = new MimeMessage(m.sessionFCN()); 
                        msg.setFrom(new InternetAddress("*****@gmail.com")); //_from
                        msg.setRecipients(MimeMessage.RecipientType.TO, "*****@hotmail.com"); //addressTo
                        msg.setSubject("Ciao Ciao"); 
                        msg.setSentDate(new Date()); 

                        // setup message body 
                        BodyPart messageBodyPart = new MimeBodyPart();  
                        messageBodyPart.setText("You never know... :)"); //_body
                        Multipart _multipart;
                        _multipart = new MimeMultipart();
                        _multipart.addBodyPart(messageBodyPart); 

                        // Put parts in message 
                        try 
                        {
                        msg.setContent(_multipart);
                        } 
                        catch (Exception e) 
                        {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } 

                        // send email 
                        try 
                        {
                            Transport.send(msg);
                        } 
                        catch (Exception e) 
                        {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            Log.e("PICTURE TAKEN", "ERROR WITH Transport.send(msg)");
                        }
                    //END SEND
                    //m.send();
                    }
                    catch (Exception e)
                    {
                        tv1.setText("Sending Failed");
                    }

                    //try 
                    //{
                    //  Thread.sleep(500);
                    //} 
                    //catch (InterruptedException e) 
                    //{
                    //  // TODO Auto-generated catch block
                    //  e.printStackTrace();
                    //}

                }
                //camera.startPreview();
            }
        }
    };

    private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) 
    {
      Camera.Size result=null;

      for (Camera.Size size : parameters.getSupportedPreviewSizes()) 
      {
        if (size.width<=width && size.height<=height) 
        {
          if (result==null) 
          {
            result=size;
          }
          else 
          {
            int resultArea=result.width*result.height;
            int newArea=size.width*size.height;

            if (newArea>resultArea) 
            {
              result=size;
            }
          }
        }
      }

      return(result);
    }

    private void initPreview(int width, int height) 
    {
      if (camera!=null && previewHolder.getSurface()!=null) 
      {
        try 
        {
          camera.setPreviewDisplay(previewHolder);
        }
        catch (Throwable t) 
        {
          Log.e("PreviewDemo-surfaceCallback", "Exception in setPreviewDisplay()", t);
          //Toast.makeText(PreviewDemo.this, t.getMessage(), Toast.LENGTH_LONG).show();
        }

        if (!cameraConfigured) 
        {
          Camera.Parameters parameters=camera.getParameters();
          Camera.Size size=getBestPreviewSize(width, height, parameters);

          if (size!=null) 
          {
            parameters.setPreviewSize(size.width, size.height);
            camera.setParameters(parameters);
            cameraConfigured=true;
          }
        }
      }
    }

    private void startPreview() 
    {
      if (cameraConfigured && camera!=null) 
      {
        camera.startPreview();
        inPreview=true;
      }
    }

    SurfaceHolder.Callback surfaceCallback=new SurfaceHolder.Callback() 
    {
      public void surfaceCreated(SurfaceHolder holder) 
      {
        // no-op -- wait until surfaceChanged()
      }

      public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) 
      {
        initPreview(width, height);
        startPreview();
      }

      public void surfaceDestroyed(SurfaceHolder holder) 
      {
        // no-op
      }
    };

    public void initialize(Context c)
    {
        //Log.e("initialize", "Setting content view");
        //setContentView(R.layout.main);
        //Log.e("initialize", "Content View Set");
        //Log.e("initialize", "Initialization started");
        //preview=(SurfaceView)this.findViewById(R.id.preview);
        //Log.e("initialize", "preview set");
        //previewHolder=preview.getHolder();
        //previewHolder.addCallback(surfaceCallback);
        //previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        //Log.e("initialize", "holder set");
        //colorREDsum = 0;
    }

}

As a matter of completness, I am posting also the class I use to send emails: 作为完善性的问题,我还将发布用于发送电子邮件的课程:

package com.lyo.android.CameraSender5;

import java.util.Date; 
import java.util.Properties; 
import javax.activation.CommandMap; 
import javax.activation.DataHandler; 
import javax.activation.DataSource; 
import javax.activation.FileDataSource; 
import javax.activation.MailcapCommandMap; 
import javax.mail.BodyPart; 
import javax.mail.Multipart; 
import javax.mail.PasswordAuthentication; 
import javax.mail.Session; 
import javax.mail.Transport; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeBodyPart; 
import javax.mail.internet.MimeMessage; 
import javax.mail.internet.MimeMultipart; 
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class Mail extends javax.mail.Authenticator 
{ 
  private String _user; 
  private String _pass; 

  private String[] _to; 
  private String _from; 

  private String _port; 
  private String _sport; 

  private String _host; 

  private String _subject; 
  private String _body; 

  private boolean _auth; 

  private boolean _debuggable; 

  private Multipart _multipart; 


  public Mail() 
  { 
    _host = "smtp.gmail.com"; // default smtp server 
    _port = "465"; // default smtp port 
    _sport = "465"; // default socketfactory port 

    _user = "*****@gmail.com"; // username 
    _pass = "*****"; // password 
    _from = "*****@gmail.com"; // email sent from 
    _subject = "Ciao Ciao"; // email subject 
    _body = "You never know... :)"; // email body 

    _debuggable = false; // debug mode on or off - default off 
    _auth = true; // smtp authentication - default on 

    _multipart = new MimeMultipart(); 

    // There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added. 
    MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); 
    mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); 
    mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); 
    mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); 
    mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); 
    mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); 
    CommandMap.setDefaultCommandMap(mc); 
  } 

  public Mail(String user, String pass) { 
    this(); 

    _user = user; 
    _pass = pass; 
  } 

  //mie

  public Session sessionFCN()
  {
      Properties props = _setProperties();
      Session session;
    try {
        Log.e("SESSION","TRYING Session.getInstance");
        session = Session.getInstance(props, new GMailAuthenticator("*****@gmail.com", "*****"));
    return session;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.e("SESSION","ERROR WITH Session.getInstance");
    }
      //DUMMY
    session = Session.getInstance(props, new GMailAuthenticator("*****@gmail.com", "*****"));
    return session;
  }

  class GMailAuthenticator extends Authenticator {
         String user;
         String pw;
         public GMailAuthenticator (String username, String password)
         {
            super();
            this.user = username;
            this.pw = password;
         }
        public PasswordAuthentication getPasswordAuthentication()
        {
           return new PasswordAuthentication(user, pw);
        }
    }

  //stop mie

  public boolean send() throws Exception { 
    Properties props = _setProperties(); 

    if(!"*****@gmail.com".equals("") && !"*****".equals("") && _to.length > 0 && !"*****@gmail.com".equals("") && !"Ciao Ciao".equals("") && !"You never know... :)".equals("")) 
    { 

      Session session = Session.getInstance(props, this); 
      MimeMessage msg = new MimeMessage(session); 
      msg.setFrom(new InternetAddress("*****@gmail.com")); //_from
      InternetAddress[] addressTo = new InternetAddress[_to.length]; 
      for (int i = 0; i < _to.length; i++) 
      { 
        addressTo[i] = new InternetAddress(_to[i]); 
      } 
      msg.setRecipients(MimeMessage.RecipientType.TO, addressTo); 
      msg.setSubject("Ciao Ciao"); 
      msg.setSentDate(new Date()); 
      //

      // setup message body 
      BodyPart messageBodyPart = new MimeBodyPart();  
      messageBodyPart.setText("You never know... :)"); //_body
      _multipart.addBodyPart(messageBodyPart); 

      // Put parts in message 
      msg.setContent(_multipart); 

      // send email 
      Transport.send(msg); 

      return true; 
    } 
    else 
    { 
      return false; 
    } 
  } 

  //You can call this method at any time if you want to add an attachment, but make sure you call it before the send method.
  public void addAttachment(String filename) throws Exception 
  { 
    BodyPart messageBodyPart = new MimeBodyPart(); 
    DataSource source = new FileDataSource(filename); 
    messageBodyPart.setDataHandler(new DataHandler(source)); 
    messageBodyPart.setFileName(filename); 

    _multipart.addBodyPart(messageBodyPart); 
  } 

  @Override 
  public PasswordAuthentication getPasswordAuthentication() 
  { 
    return new PasswordAuthentication(_user, _pass); 
  } 

  public Properties _setProperties() //private
  { 
    Properties props = new Properties(); 

    props.put("mail.smtp.host", _host); 

    if(_debuggable) 
    { 
      props.put("mail.debug", "true"); 
    } 

    if(_auth) 
    { 
      props.put("mail.smtp.auth", "true"); 
    } 

    props.put("mail.smtp.port", _port); 
    props.put("mail.smtp.socketFactory.port", _sport); 
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 
    props.put("mail.smtp.socketFactory.fallback", "false"); 

    return props; 
  } 

  // the getters and setters 
  public String getBody() 
  { 
    return _body; 
  } 

  public void setBody(String _body) 
  { 
    this._body = _body; 
  } 

  // more of the getters and setters ….. 
  public void setTo(String[] toArr) 
  {
    this._to = toArr;
  }

  public void setFrom(String string) 
  {
    this._from = string;
  }

  public void setSubject(String string) 
  {
    this._subject = string;
  } 
  };

Thanks to the Log.e messages, I found that the error occurrs on the camera = Camera.open(); 多亏了Log.e消息,我发现在camera = Camera.open();上发生了错误。 The following is the LogCat I get from Eclipse: 以下是我从Eclipse获得的LogCat:

08-03 22:00:24.135: E/onCreate(1817): onCreate started
08-03 22:00:24.205: E/onCreate(1817): ContentView set
08-03 22:00:24.215: E/onCreate(1817): TakePic called
08-03 22:00:24.215: E/onCreate(1817): Initialized
08-03 22:00:27.295: E/LYO TakePic onCreate(1817): Setting content view
08-03 22:00:27.305: E/LYO TakePic onCreate(1817): Content View Set
08-03 22:00:27.305: E/LYO TakePic onCreate(1817): Initialization started
08-03 22:00:27.305: E/LYO TakePic onCreate(1817): preview set
08-03 22:00:27.305: E/LYO TakePic onCreate(1817): holder set
08-03 22:00:27.305: E/LYO TakePic onResume(1817): CAMERA NULL
08-03 22:00:27.305: E/LYO TakePic onResume(1817): onResume Start
08-03 22:00:27.325: E/AndroidRuntime(1817): FATAL EXCEPTION: main
08-03 22:00:27.325: E/AndroidRuntime(1817): java.lang.RuntimeException: Unable to resume activity {com.lyo.android.CameraSender5/com.lyo.android.CameraSender5.TakePic}: java.lang.RuntimeException: Fail to connect to camera service
08-03 22:00:27.325: E/AndroidRuntime(1817):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3128)
08-03 22:00:27.325: E/AndroidRuntime(1817):     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3143)
08-03 22:00:27.325: E/AndroidRuntime(1817):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2684)
08-03 22:00:27.325: E/AndroidRuntime(1817):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
08-03 22:00:27.325: E/AndroidRuntime(1817):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
08-03 22:00:27.325: E/AndroidRuntime(1817):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-03 22:00:27.325: E/AndroidRuntime(1817):     at android.os.Looper.loop(Looper.java:123)
08-03 22:00:27.325: E/AndroidRuntime(1817):     at android.app.ActivityThread.main(ActivityThread.java:4627)
08-03 22:00:27.325: E/AndroidRuntime(1817):     at java.lang.reflect.Method.invokeNative(Native Method)
08-03 22:00:27.325: E/AndroidRuntime(1817):     at java.lang.reflect.Method.invoke(Method.java:521)
08-03 22:00:27.325: E/AndroidRuntime(1817):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-03 22:00:27.325: E/AndroidRuntime(1817):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-03 22:00:27.325: E/AndroidRuntime(1817):     at dalvik.system.NativeStart.main(Native Method)
08-03 22:00:27.325: E/AndroidRuntime(1817): Caused by: java.lang.RuntimeException: Fail to connect to camera service
08-03 22:00:27.325: E/AndroidRuntime(1817):     at android.hardware.Camera.native_setup(Native Method)
08-03 22:00:27.325: E/AndroidRuntime(1817):     at android.hardware.Camera.<init>(Camera.java:110)
08-03 22:00:27.325: E/AndroidRuntime(1817):     at android.hardware.Camera.open(Camera.java:90)
08-03 22:00:27.325: E/AndroidRuntime(1817):     at com.lyo.android.CameraSender5.TakePic.onResume(TakePic.java:107)
08-03 22:00:27.325: E/AndroidRuntime(1817):     at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1149)
08-03 22:00:27.325: E/AndroidRuntime(1817):     at android.app.Activity.performResume(Activity.java:3823)
08-03 22:00:27.325: E/AndroidRuntime(1817):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3118)
08-03 22:00:27.325: E/AndroidRuntime(1817):     ... 12 more

As you can see, I am trying to release/unlock the camera before calling it, just to make sure it is not being already used, but I still get the same error... what am I doing wrong? 如您所见,我在尝试调用相机之前试图释放/解锁它,只是为了确保它尚未被使用,但是我仍然遇到相同的错误……我在做什么错?

Thank you in advance for your help! 预先感谢您的帮助!

I stumbled upon this post and it wasn't clear that the OP had resolved until I read his/her comment, I am posting this only for future stumblers (No up-votes/down-votes please). 我偶然发现了此帖子,直到我阅读他/她的评论后,OP才解决。我仅将其发布给以后的绊脚石(请不要上投票/下投票)。


As per the users comment: 根据用户评论:

I somehow found the way to make it work. 我以某种方式找到了使其工作的方法。 The problem was that I was not calling properly the TakePic.java from my main activity. 问题是我没有从主要活动中正确调用TakePic.java

Instead of: 代替:

startActivity(new Intent("com.lyo.android.TAKEPIC")); 

I have to use the following: 我必须使用以下内容:

final Intent takePic = new Intent(this, TakePic.class);
takePic.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
takePic.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
startActivity(takePic); 

I still had problem when calling this recursively, but I solved it by implementing the timer itself in the TakePic.java 递归调用时仍然有问题,但是我通过在TakePic.java实现计时器本身解决了它

I somehow found the way to make it work. 我以某种方式找到了使其工作的方法。 The problem was that I was not calling properly the TakePic.java from my main activity. 问题是我没有从主要活动中正确调用TakePic.java Instead of: 代替:

startActivity(new Intent("com.lyo.android.TAKEPIC")); 

I have to use the following: 我必须使用以下内容:

final Intent takePic = new Intent(this, TakePic.class);
takePic.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
takePic.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
startActivity(takePic); 

I still had problem when calling this recursively, but I solved it by implementing the timer itself in the TakePic.java 递归调用时仍然有问题,但是我通过在TakePic.java实现计时器本身解决了它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM