0

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. 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. 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

<?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:

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):

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(); The following is the LogCat I get from Eclipse:

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!

  • 1
    Should you return to the beloved StackOverflow site, would you be so kindly as to add your above comment as an answer and accept it. In your absence I have posted an answer for future visitors, please do not accept mine. – jnthnjns Mar 08 '13 at 20:46

2 Answers2

0

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).


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.

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

Community
  • 1
  • 1
jnthnjns
  • 8,962
  • 4
  • 42
  • 65
0

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. 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

Achrome
  • 7,773
  • 14
  • 36
  • 45