Wikipedia

Search results

Saturday, July 13, 2013

Animation Tutorial

Animation Image Used in Android Tutorial

GIF Image used in Android Application. for that you need to use following code implementation in your android project.



That is the UI of this tutorial demo for Android.


public AnimationView(Context context,AttributeSet attrs) {
      super(context,attrs);
      setFocusable(true);
      java.io.InputStream is;
      is = context.getResources().openRawResource(R.drawable.th_welcome);
      if (DECODE_STREAM) {
        mMovie = Movie.decodeStream(is);
      } else {
        byte[] array = streamToBytes(is);
        mMovie = Movie.decodeByteArray(array, 0, array.length);
      }
    }

Other things to draw Canvas can be used the following code.

@Override
    public void onDraw(Canvas canvas) {
     long now = android.os.SystemClock.uptimeMillis();
      if (mMovieStart == 0) { // first time
        mMovieStart = now;
      }
      if (mMovie != null) {
        int dur = mMovie.duration();
        if (dur == 0) {
          dur = 3000;
        }
        int relTime = (int) ((now - mMovieStart) % dur);
       Log.d("", "real time :: " +relTime);
        mMovie.setTime(relTime);
        mMovie.draw(canvas, getWidth() - 200, getHeight()-200);
        invalidate();
      }
    }

       


For Source Code click here to Download.


             http://androidcheatapps.com/

Monday, June 17, 2013

Custom Gallery View

Custom View for Gallery Demo in Android.

 

Declare following variables.

  
private ImageView selectedImageView;
private ImageView leftArrowImageView;
private ImageView rightArrowImageView;
private Gallery gallery;
private int selectedImagePosition = 0;
private List<Drawable> drawables;
private GalleryImageAdapter galImageAdapter;

 

Screen-Snap 

private void setupUI() {



selectedImageView = (ImageView) findViewById(R.id.selected_imageview);
  leftArrowImageView = (ImageView) findViewById(R.id.left_arrow_imageview);
  rightArrowImageView = (ImageView) findViewById(R.id.right_arrow_imageview);
  gallery = (Gallery) findViewById(R.id.gallery);

  leftArrowImageView.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {

    if (selectedImagePosition > 0) {
     --selectedImagePosition;

    }

    gallery.setSelection(selectedImagePosition, false);
   }
  });

  rightArrowImageView.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {

    if (selectedImagePosition < drawables.size() - 1) {
     ++selectedImagePosition;

    }

    gallery.setSelection(selectedImagePosition, false);

   }
  });


This Function used for Gallary Images selection purpose, and to swap left and right you also use arrow buttons which works with this function.


gallery.setOnItemSelectedListener(new OnItemSelectedListener() {

   @Override
   public void onItemSelected(AdapterView parent, View view, int pos, long id) {

    selectedImagePosition = pos;

    if (selectedImagePosition > 0 && selectedImagePosition < drawables.size() - 1) {

     leftArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_left_enabled));
     rightArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_right_enabled));

    } else if (selectedImagePosition == 0) {

     leftArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_left_disabled));

    } else if (selectedImagePosition == drawables.size() - 1) {

     rightArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_right_disabled));
    }

    changeBorderForSelectedImage(selectedImagePosition);
    setSelectedImage(selectedImagePosition);
   }

   @Override
   public void onNothingSelected(AdapterView arg0) {

   }

  });


Gallary clickListener set for that selection.



galImageAdapter = new GalleryImageAdapter(this, drawables);

  gallery.setAdapter(galImageAdapter);

  if (drawables.size() > 0) {

   gallery.setSelection(selectedImagePosition, false);

  }

  if (drawables.size() == 1) {

   rightArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_right_disabled));
  }


Instantiate the Adapter and check condition for length of Images available.

 

private void changeBorderForSelectedImage(int selectedItemPos) {

  int count = gallery.getChildCount();

  for (int i = 0; i < count; i++) {

   ImageView imageView = (ImageView) gallery.getChildAt(i);
   imageView.setBackgroundDrawable(getResources().getDrawable(R.drawable.image_border));
   imageView.setPadding(3, 3, 3, 3);

  }

  ImageView imageView = (ImageView) gallery.getSelectedView();
  imageView.setBackgroundDrawable(getResources().getDrawable(R.drawable.selected_image_border));
  imageView.setPadding(3, 3, 3, 3);
 }




For selection Image border set because its view as it is selected. 

 

private void getDrawablesList() {

  drawables = new ArrayList();
  drawables.add(getResources().getDrawable(R.drawable.natureimage1));
  drawables.add(getResources().getDrawable(R.drawable.natureimage2));
  drawables.add(getResources().getDrawable(R.drawable.natureimage3));
  drawables.add(getResources().getDrawable(R.drawable.natureimage4));
  drawables.add(getResources().getDrawable(R.drawable.natureimage5));
  drawables.add(getResources().getDrawable(R.drawable.natureimage6));
  drawables.add(getResources().getDrawable(R.drawable.natureimage7));
  drawables.add(getResources().getDrawable(R.drawable.natureimage8));
  drawables.add(getResources().getDrawable(R.drawable.natureimage9));
  drawables.add(getResources().getDrawable(R.drawable.natureimage10));
  drawables.add(getResources().getDrawable(R.drawable.natureimage11));
  drawables.add(getResources().getDrawable(R.drawable.natureimage12));
  drawables.add(getResources().getDrawable(R.drawable.natureimage13));
  drawables.add(getResources().getDrawable(R.drawable.natureimage14));
  drawables.add(getResources().getDrawable(R.drawable.natureimage15));

 }




This function used to set Images in Gallary. 

 

private void setSelectedImage(int selectedImagePosition) {

  BitmapDrawable bd = (BitmapDrawable) drawables.get(selectedImagePosition);
  Bitmap b = Bitmap.createScaledBitmap(bd.getBitmap(), (int) (bd.getIntrinsicHeight() * 0.9), (int) (bd.getIntrinsicWidth() * 0.7), false);
  selectedImageView.setImageBitmap(b);
  selectedImageView.setScaleType(ScaleType.FIT_XY);

 }




Used for Image Selection.  

Following Class extends BaseAdapter and it is for set Images to the GallaryView.

 

 GalleryImageAdapter.java 

package com.sandy.gallerydemo;

import java.util.List;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

public class GalleryImageAdapter extends BaseAdapter {

 private Activity context;

 private static ImageView imageView;

 private List plotsImages;

 private static ViewHolder holder;

 public GalleryImageAdapter(Activity context, List plotsImages) {

  this.context = context;
  this.plotsImages = plotsImages;

 }

 @Override
 public int getCount() {
  return plotsImages.size();
 }

 @Override
 public Object getItem(int position) {
  return null;
 }

 @Override
 public long getItemId(int position) {
  return 0;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {

  if (convertView == null) {

   holder = new ViewHolder();

   imageView = new ImageView(this.context);

   imageView.setPadding(3, 3, 3, 3);

   convertView = imageView;

   holder.imageView = imageView;

   convertView.setTag(holder);

  } else {

   holder = (ViewHolder) convertView.getTag();
  }

  holder.imageView.setImageDrawable(plotsImages.get(position));

  holder.imageView.setScaleType(ImageView.ScaleType.FIT_XY);
  holder.imageView.setLayoutParams(new Gallery.LayoutParams(150, 90));

  return imageView;
 }

 private static class ViewHolder {
  ImageView imageView;
 }
}




For UI Design create .xml file from following reference.

 

main.xml 



  



For Source Code click here to Download. 


http://androidcheatapps.com/ 

Friday, June 14, 2013

Swap3D

Swap Views in 3D.


3D flip makes a nice effect. It seems like there is no good android implementation on the internet that shows how to make two generic view flip with each other.





Like this you flip your views as per your requirements.


Rotation.java 
=====================================

 package com.sandy.swap3d;

import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.graphics.Camera;
import android.graphics.Matrix;

public class Rotation extends Animation {
    private final float mFromDegrees;
    private final float mToDegrees;
    private final float mCenterX;
    private final float mCenterY;
    private final float mDepthZ;
    private final boolean mReverse;
    private Camera mCamera;

  
    public Rotation(float fromDegrees, float toDegrees,
            float centerX, float centerY, float depthZ, boolean reverse) {
        mFromDegrees = fromDegrees;
        mToDegrees = toDegrees;
        mCenterX = centerX;
        mCenterY = centerY;
        mDepthZ = depthZ;
        mReverse = reverse;
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
        mCamera = new Camera();
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        final float fromDegrees = mFromDegrees;
        float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

        final float centerX = mCenterX;
        final float centerY = mCenterY;
        final Camera camera = mCamera;

        final Matrix matrix = t.getMatrix();

        camera.save();
        if (mReverse) {
            camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
        } else {
            camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
        }
        camera.rotateY(degrees);
        camera.getMatrix(matrix);
        camera.restore();

        matrix.preTranslate(-centerX, -centerY);
        matrix.postTranslate(centerX, centerY);
    }
} 
Swap3D.java 
=========================================

package com.sandy.swap3d;

import com.bogotobogo.swap3d.R;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;

public class Swap3D extends Activity implements
        AdapterView.OnItemClickListener, View.OnClickListener {
    private ListView mPhotosList;
    private ViewGroup mContainer;
    private ImageView mImageView;

    // Names of the photos we show in the list
    private static final String[] PHOTOS_NAMES = new String[] {
            "Brasil",
            "Arctic",
            "Antarctica",
            "Mongolia",
            "Madagascar"
    };

    // Resource identifiers for the photos we want to display
    private static final int[] PHOTOS_RESOURCES = new int[] {
            R.drawable.p1,
            R.drawable.p2,
            R.drawable.p3,
            R.drawable.p4,
            R.drawable.p5
    };

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

        setContentView(R.layout.main);

        mPhotosList = (ListView) findViewById(android.R.id.list);
        mImageView = (ImageView) findViewById(R.id.picture);
        mContainer = (ViewGroup) findViewById(R.id.container);

        // Prepare the ListView
        final ArrayAdapter adapter = new ArrayAdapter(this,
                android.R.layout.simple_list_item_1, PHOTOS_NAMES);

        mPhotosList.setAdapter(adapter);
        mPhotosList.setOnItemClickListener(this);

        // Prepare the ImageView
        mImageView.setClickable(true);
        mImageView.setFocusable(true);
        mImageView.setOnClickListener(this);

        // Since we are caching large views, we want to keep their cache
        // between each animation
        mContainer.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);
    }

    /**
     * Setup a new 3D rotation on the container view.
     *
     * @param position the item that was clicked to show a picture, or -1 to show the list
     * @param start the start angle at which the rotation must begin
     * @param end the end angle of the rotation
     */
    private void applyRotation(int position, float start, float end) {
        // Find the center of the container
        final float centerX = mContainer.getWidth() / 2.0f;
        final float centerY = mContainer.getHeight() / 2.0f;

        // Create a new 3D rotation with the supplied parameter
        // The animation listener is used to trigger the next animation
        final Rotation rotation =
                new Rotation(start, end, centerX, centerY, 310.0f, true);
        rotation.setDuration(500);
        rotation.setFillAfter(true);
        rotation.setInterpolator(new AccelerateInterpolator());
        rotation.setAnimationListener(new DisplayNextView(position));

        mContainer.startAnimation(rotation);
    }

    public void onItemClick(AdapterView parent, View v, int position, long id) {
        // Pre-load the image then start the animation
        mImageView.setImageResource(PHOTOS_RESOURCES[position]);
        applyRotation(position, 0, 90);
    }

    public void onClick(View v) {
        applyRotation(-1, 180, 90);
    }

    /**
     * This class listens for the end of the first half of the animation.
     * It then posts a new action that effectively swaps the views when the container
     * is rotated 90 degrees and thus invisible.
     */
    private final class DisplayNextView implements Animation.AnimationListener {
        private final int mPosition;

        private DisplayNextView(int position) {
            mPosition = position;
        }

        public void onAnimationStart(Animation animation) {
        }

        public void onAnimationEnd(Animation animation) {
            mContainer.post(new SwapViews(mPosition));
        }

        public void onAnimationRepeat(Animation animation) {
        }
    }

    /**
     * This class is responsible for swapping the views and start the second
     * half of the animation.
     */
    private final class SwapViews implements Runnable {
        private final int mPosition;

        public SwapViews(int position) {
            mPosition = position;
        }

        public void run() {
            final float centerX = mContainer.getWidth() / 2.0f;
            final float centerY = mContainer.getHeight() / 2.0f;
            Rotation rotation;
           
            if (mPosition > -1) {
                mPhotosList.setVisibility(View.GONE);
                mImageView.setVisibility(View.VISIBLE);
                mImageView.requestFocus();

                rotation = new Rotation(90, 180, centerX, centerY, 310.0f, false);
            } else {
                mImageView.setVisibility(View.GONE);
                mPhotosList.setVisibility(View.VISIBLE);
                mPhotosList.requestFocus();

                rotation = new Rotation(90, 0, centerX, centerY, 310.0f, false);
            }

            rotation.setDuration(5000);
            rotation.setFillAfter(true);
            rotation.setInterpolator(new DecelerateInterpolator());

            mContainer.startAnimation(rotation);
        }
    }
} 
main.xml 
================================


    

    



For Source Code click here to Download. 

Time and Date Piker

Time and Date piker both are in single dialog.


Android provides controls for the user to pick a time or pick a date as ready-to-use dialogs. Each picker provides controls for selecting each part of the time (hour, minute, AM/PM) or date (month, day, year). Using these pickers helps ensure that your users can pick a time or date that is valid, formatted correctly, and adjusted to the user's locale.




We recommend that you use Dialog Fragment to host each time or date picker. The Dialog Fragment manages the dialog life-cycle for you and allows you to display the pickers in different layout configurations, such as in a basic dialog on handsets or as an embedded part of the layout on large screens.



Note: 
The code samples below show how to create dialogs for a time picker and date picker using the support Library APIs for Dialog Fragment. If your app's minsdkVersion is 11 or higher, you can instead use the platform version of Dialog Fragment.


Time Piker

  • Define the onCreateDialog() method to return an instance of TimePikerDialog
  • Implement the TimePikerDialog.onTimeSetListener() interface to receive a callback when the user sets the time.

Here's an example:
================================================================
public static class TimePickerFragment extends DialogFragment
                            implements TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        // Do something with the time chosen by the user
    }
}
 =========================================================================
 
 
Date Piker
 
  • Define the onCreateDialog() method to return an instance of DatePikerDialog
  • Implement the DatePikerDialog.onDateSetListener() interface to receive a callback when the user sets the date.

Here's an example:
================================================================
public static class DatePickerFragment extends DialogFragment
                            implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
    }
}
=============================================================================
 
 
For Source Code Click on Download. 

 
 

StartAppDemo

StartApp Advertisement tutoril for android applications.


Simple Demo that show how the StartApp SDK works.

We have found a new way to generate some money from this free app. using this new search tool, we can keep creating apps and give them to you completely free forever!  

This search is from our search partner and give you access to great web search via a search icon, bookmark link and homepage. You may remove them at your choice.



 Have you found a strange search icon on your home screen?
 Have you found a strange browser search home page?
 Have you found a strange bookmark links?

 Don't worry, it's nothing dangerous. This application tells you what is StartApp and how it works.






you use following code for that class.



.JAVA code
================================================================

private HtmlAd htmlAd = null;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn = (Button) findViewById(R.id.button1);
       
        AndroidSDKProvider.setTestMode(true);
        AndroidSDKProvider.initSDK(MainActivity.this);
        AdPreferences adPreferences = new AdPreferences("112311471","206506517",AdPreferences.TYPE_INAPP_EXIT);
        htmlAd = new HtmlAd(this);
        htmlAd.load(adPreferences, this);
       
        btn.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if(htmlAd != null) {
                    htmlAd.show();
                }
            }
        });
    }

   
    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
   
        if(htmlAd != null) {
            htmlAd.show();
        }
       
        super.onBackPressed();
    }


    @Override
    public void onFailedToReceiveAd(Ad arg0) {
        // TODO Auto-generated method stub
       
    }

    @Override
    public void onReceiveAd(Ad arg0) {
        // TODO Auto-generated method stub
       
    }
   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

 

================================================================



This type of popup you show.


.XML code
================================================================


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Go Back for Add or Click on Button" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:text="Show Start App Add." />

</RelativeLayout>


================================================================


Also it required more user-permissions in their manifest file.

There is a following code put into manifest file for give permissions.


Manifest.xml
================================================================ 


<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
    <uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />
    <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
    <uses-permission android:name="com.htc.launcher.permission.READ_SETTINGS" />
    <uses-permission android:name="com.motorola.launcher.permission.READ_SETTINGS" />
    <uses-permission android:name="com.motorola.dlauncher.permission.READ_SETTINGS" />
    <uses-permission android:name="com.fede.launcher.permission.READ_SETTINGS" />
    <uses-permission android:name="com.lge.launcher.permission.READ_SETTINGS" />
    <uses-permission android:name="org.adw.launcher.permission.READ_SETTINGS" />
    <uses-permission android:name="com.motorola.launcher.permission.INSTALL_SHORTCUT" />
    <uses-permission android:name="com.motorola.dlauncher.permission.INSTALL_SHORTCUT" />
    <uses-permission android:name="com.lge.launcher.permission.INSTALL_SHORTCUT" />
    <uses-permission android:name="com.android.browser.permission.WRITE_HISTORY_BOOKMARKS" />
    <uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS" />
    <uses-permission android:name="com.android.launcher.permission.WRITE_SETTINGS" />
    <uses-permission android:name="com.htc.launcher.permission.WRITE_SETTINGS" />
    <uses-permission android:name="com.motorola.launcher.permission.WRITE_SETTINGS" />
    <uses-permission android:name="com.motorola.dlauncher.permission.WRITE_SETTINGS" />
    <uses-permission android:name="com.lge.launcher.permission.WRITE_SETTINGS" />
    <uses-permission android:name="com.fede.launcher.permission.WRITE_SETTINGS" />
    <uses-permission android:name="org.adw.launcher.permission.WRITE_SETTINGS" />



<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.startappdemo.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name="com.apperhand.device.android.AndroidSDKProvider"
            android:enabled="true" />

        <activity
            android:name="com.apperhand.device.android.EULAActivity"
            android:configChanges="keyboard|keyboardHidden|orientation"
            android:theme="@android:style/Theme.Translucent" />
        <activity
            android:name="com.startapp.android.publish.AppWallActivity"
            android:configChanges="orientation|keyboardHidden"
            android:theme="@android:style/Theme.Translucent" />
       
       
        <meta-data android:name="com.startapp.android.DEV_ID" android:value= "DEV_ID_HERE"/>
        <meta-data android:name="com.startapp.android.APP_ID" android:value= "APP_ID_HERE"/>
       
    </application>
 
================================================================ 

 

For more information you click here.

For Source Code Download Click here.


Tuesday, June 11, 2013

Capture On Surface Pro

Surface cameras

Surface has not just one, but two integrated LifeCam cameras. You can use the front camera to have a video chat with a friend, or the rear-facing camera to record meetings and events hands-free. You can also use either camera to take photos.







A privacy light appears on Surface when either camera is active, so there are no surprises. Both cameras are fixed focus, so you don’t need to worry about focusing. The cameras capture video in 720p HD, with a 16:9 aspect ratio.
Both cameras take photos and record videos. The rear camera is angled to point straight ahead when Surface is resting on its kickstand or when you hold your Surface at a viewing angle that’s comfortable for your wrists.






The front camera points up at your face for optimal video calling.



Surface cameras FAQ

Here are answers to some common questions about using the two Surface cameras and the built-in Camera app.
  • How do I get started using the cameras?
  • Why can I take photos but not videos (or the reverse)?
  • Is the camera facing the wrong way?
  • Why does the camera angle seem wrong?
  • How do I turn off the camera click?
  • Can I use both cameras at the same time?
  • How do I turn off the camera privacy light?

Following class for Custom CameraView.

CameraOnSurfaceProActivity.java

 package com.CameraOnSurfacePro;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuffXfermode;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class CameraOnSurfaceProActivity extends Activity implements SurfaceHolder.Callback{

    Camera camera;
    SurfaceView surfaceView;
    SurfaceHolder surfaceHolder;
    boolean previewing = false;
  
    byte[] bArray;
  
    Uri outputFileUri;
    Bitmap correctBmp;  
    LinearLayout ll_flipcamera;
  
    static Boolean camera_bool = false;
    Bitmap bitmapPicture;
    Bitmap scaled;
  
    Bitmap newTemp;
  
    public static int noOfCamera;
    public static boolean enableFrontCamera = false;
  
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
      
        noOfCamera = Camera.getNumberOfCameras();
        ll_flipcamera = (LinearLayout) findViewById(R.id.ll_flipcamera);

        if(noOfCamera > 1)
        {
            enableFrontCamera=true;
        }
        else
        {
            ll_flipcamera.setVisibility(View.GONE);
        }
      
        Button capture = (Button)findViewById(R.id.capture);
      
        Button flip_camera = (Button) findViewById(R.id.flip_camera);
      
        getWindow().setFormat(PixelFormat.UNKNOWN);
        surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
      
        flip_camera.setOnClickListener(new OnClickListener() {
          
            public void onClick(View v) {
              
                if(camera_bool){
                      
                    camera.release();
                    camera = null;
                    previewing = false;
                    camera = Camera.open(0);
                  
                    if (camera != null){
                        try {
                            camera.setDisplayOrientation(90);
                            camera.setPreviewDisplay(surfaceHolder);
                            camera.startPreview();
                            previewing = false;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    camera_bool = false;
                }else{
                      
                    camera.release();
                    camera = null;
                    previewing = false;
                    camera = Camera.open(1);
                  
                    if (camera != null){
                        try {
                            camera.setDisplayOrientation(90);
                            camera.setPreviewDisplay(surfaceHolder);
                            camera.startPreview();
                            previewing = false;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    camera_bool = true;
                }
            }
        });
      
        capture.setOnClickListener(new Button.OnClickListener()
        {

            @Override
            public void onClick(View v) {
              
                if(camera != null)
                {
                    camera.takePicture(myShutterCallback, myPictureCallback_RAW, myPictureCallback_JPG);
//                    System.gc();
                }
            }
        });
    }
  
    @Override
    protected void onResume() {
        super.onResume();
        startCamera();
    }
  
    public void startCamera() {
        if(!previewing){
            camera = Camera.open(0);
            if (camera != null){
                try {
                    camera.setDisplayOrientation(90);
                    camera.setPreviewDisplay(surfaceHolder);
                    camera.startPreview();
                    previewing = false;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    ShutterCallback myShutterCallback = new ShutterCallback(){

        @Override
        public void onShutter() {
          
        }};
      
    PictureCallback myPictureCallback_RAW = new PictureCallback(){

        @Override
        public void onPictureTaken(byte[] arg0, Camera arg1) {
          
        }};
    PictureCallback myPictureCallback_JPG = new PictureCallback(){
      
      
        @Override
        public void onPictureTaken(byte[] arg0, Camera arg1) {
          
            bArray = arg0;
          
            bitmapPicture = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
          
          
            Matrix mat = new Matrix();
            mat.postRotate(90);

            correctBmp = null;
            correctBmp = Bitmap.createBitmap(bitmapPicture, 0, 0, bitmapPicture.getWidth(), bitmapPicture.getHeight(), null, true);
          
            Bitmap correctBmp1 = correctBmp;
          
            OutputStream os = null;
            try
            {
                File root = new File(Environment.getExternalStorageDirectory() + "/CDD/");
                root.mkdirs();
                File sdImageMainDirectory = new File(root, "myPicOriginal.jpg");
                outputFileUri = Uri.fromFile(sdImageMainDirectory);
                os = new FileOutputStream(sdImageMainDirectory);

                os.write(arg0);
//                correctBmp.compress(Bitmap.CompressFormat.PNG, 100, os);
              
                os.flush();
                os.close();
            }
            catch (Exception e)
            {
                Toast.makeText(CameraOnSurfaceProActivity.this,
                                    "Error occured. Please try again later.",
                                    Toast.LENGTH_SHORT).show();
            }
          
            scaled = cropBitmap(correctBmp1);
          

            OutputStream fOut = null;
            try {
                File root = new File(Environment.getExternalStorageDirectory()
                        + "/CDD/");
                root.mkdirs();
                File sdImageMainDirectory = new File(root, "myPicName.jpg");
              
                outputFileUri = Uri.fromFile(sdImageMainDirectory);
                fOut = new FileOutputStream(sdImageMainDirectory);
            } catch (Exception e) {
                Toast.makeText(CameraOnSurfaceProActivity.this,
                        "Error occured. Please try again later.",
                        Toast.LENGTH_SHORT).show();
            }

            try {
              
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                scaled.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byte[] byteArray = stream.toByteArray();
              
              
                fOut.write(byteArray);
              
//                scaled.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                fOut.flush();
                fOut.close();

                scaled.recycle();
                correctBmp.recycle();
              
            } catch (Exception e) {
            }
        }};
      
        private Bitmap cropBitmap(Bitmap originalBitmap)
        {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            originalBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
          
            Bitmap bmp2 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
          
            Bitmap bmOverlay = Bitmap.createBitmap(276, 276, Bitmap.Config.ARGB_8888);

            Paint p = new Paint();
            p.setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.CLEAR));            
            Canvas c = new Canvas(bmOverlay);
            c.drawBitmap(bmp2, 100, 100, null);
            c.drawRect(0, 0, 276, 276, p);

            return bmOverlay;
        }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        if(previewing){
            camera.stopPreview();
            previewing = false;
        }
      
        if (camera != null){
            try {
                camera.setPreviewDisplay(surfaceHolder);
                camera.startPreview();
                previewing = false;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        camera.setPreviewCallback(null);
        camera.stopPreview();
        camera.release();
        camera = null;
        previewing = false;
    }
}

this capture button you have to use.



 button of flip CameraView


main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/ll_flipcamera"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="0.95"
        android:background="#2e2e2e"
        android:orientation="vertical" >

        <Button
            android:id="@+id/flip_camera"
            android:layout_width="35dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal|right"
            android:background="@drawable/flip_camera" />
    </LinearLayout>
   
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="0.05"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="0.10"
            android:orientation="vertical" >

            <SurfaceView
                android:id="@+id/surfaceview"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="0.90"
            android:background="#2e2e2e"
            android:orientation="vertical" >

           
            <Button
                android:id="@+id/capture"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:background="@drawable/capture_image111" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>




Click here to Download SourceCode.