Monday, 9 June 2014

how to create simple torch light in android

MainActivity.java

package com.simpleflashlight;

import java.io.IOException;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity implements SurfaceHolder.Callback {

    public final static String TAG = "simple torch";
    Camera cam;
    ToggleButton mTorch;
    Parameters camParams;
    private Context context;
    AlertDialog.Builder builder;
    AlertDialog alertDialog;
    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;
    private final int FLASH_NOT_SUPPORTED = 0;
    private final int FLASH_TORCH_NOT_SUPPORTED = 1;
   
      @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        context = MainActivity.this;
        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)){
            mTorch = (ToggleButton) findViewById(R.id.toggleButton);
            mTorch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    Log.d(TAG, "onCheckedChanged");
                    try{
                        if (cam == null){
                            cam = Camera.open();
                        }
                        camParams = cam.getParameters();
                        List<String> flashModes = camParams.getSupportedFlashModes();
                        if (isChecked){
                            if (flashModes.contains(Parameters.FLASH_MODE_TORCH)) {
                                camParams.setFlashMode(Parameters.FLASH_MODE_TORCH);
                            }else{
                                showDialog(MainActivity.this, FLASH_TORCH_NOT_SUPPORTED);
                            }
                        } else {
                            camParams.setFlashMode(Parameters.FLASH_MODE_OFF);
                        }
                        cam.setParameters(camParams);
                        cam.startPreview();
                    }catch (Exception e) {
                        Log.d(TAG, "Caught " + e);
                        Toast.makeText(MainActivity.this, "Camera/Torch failure: " + e, Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                        if (cam != null) {
                            cam.stopPreview();
                            cam.release();
                        }
                    }
                }
            });
            surfaceView = (SurfaceView) this.findViewById(R.id.SurfaceView);
            surfaceHolder = surfaceView.getHolder();
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
            surfaceHolder.addCallback(this);
        } else {
            showDialog(MainActivity.this, FLASH_NOT_SUPPORTED);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(cam == null){
            cam = Camera.open();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        cam.release();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(cam != null){
            cam.release();
        }
    }

    public void showDialog (Context context, int dialogId) {
        switch(dialogId){
        case FLASH_NOT_SUPPORTED:
            builder = new AlertDialog.Builder(context);
            builder.setMessage("Sorry, Your phone does not support Camera Flash")
            .setCancelable(false)
            .setNeutralButton("Close", new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            alertDialog = builder.create();
            alertDialog.show();
            break;
        case FLASH_TORCH_NOT_SUPPORTED:
            builder = new AlertDialog.Builder(context);
            builder.setMessage("Sorry, Your camera flash does not support torch feature")
            .setCancelable(false)
            .setNeutralButton("Close", new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            alertDialog = builder.create();
            alertDialog.show();
        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
     
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {

            cam.setPreviewDisplay(holder);

        } catch (IOException e) {
         

        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
     
    }   
}

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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="20dip"
        android:text="@string/app_title"
        android:textSize="25sp" />

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="20dip"
        android:text="@string/toggleButtonLabe" />

    <SurfaceView
        android:id="@+id/SurfaceView"
        android:layout_width="1dp"
        android:layout_height="1dp" />

</LinearLayout>

AndroidManifest.xml

 <uses-feature
        android:name="android.hardware.Camera"
        android:required="true" >
    </uses-feature>
    <uses-feature
        android:name="android.hardware.camera.FLASHLIGHT"
        android:required="true" >
    </uses-feature>

    <uses-permission android:name="android.permission.CAMERA" >
    </uses-permission>
   

how to use random function in android

Random function

Random rand = new Random();
int rnd = rand.nextInt(16);
System.out.println("~~~~~~"+rnd);

Wednesday, 4 June 2014

how to get gallery image in android


private void selectImage() {
        final CharSequence[] items = { "Take Photo", "Choose from gallery",
                "Cancel" };

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Photo");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Take Photo")) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File f = new File(android.os.Environment
                            .getExternalStorageDirectory(), "temp.jpg");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                    startActivityForResult(intent, REQUEST_CAMERA);
                } else if (items[item].equals("Choose from gallery")) {
                    Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(
                            Intent.createChooser(intent, "Select File"),
                            SELECT_FILE);
                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CAMERA) {
                File f = new File(Environment.getExternalStorageDirectory()
                        .toString());
                for (File temp : f.listFiles()) {
                    if (temp.getName().equals("temp.jpg")) {
                        f = temp;
                        break;
                    }
                }
                try {
                    Bitmap bm;
                    BitmapFactory.Options btmapOptions = new BitmapFactory.Options();

                    bm = BitmapFactory.decodeFile(f.getAbsolutePath(),
                            btmapOptions);

                    image.setImageBitmap(bm);

                    String path = android.os.Environment
                            .getExternalStorageDirectory()
                            + File.separator
                            + "Phoenix" + File.separator + "default";
                    f.delete();
                    OutputStream fOut = null;
                    File file = new File(path, String.valueOf(System
                            .currentTimeMillis()) + ".jpg");
                    try {
                        fOut = new FileOutputStream(file);
                        bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
                        fOut.flush();
                        fOut.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (requestCode == SELECT_FILE) {
                Uri selectedImageUri = data.getData();

                String tempPath = getPath(selectedImageUri, MainActivity.this);
                Bitmap bm;
                BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
                bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
                image.setImageBitmap(bm);
            }
        }
    }

public String getPath(Uri uri, Activity activity) {
        String[] projection = { MediaColumns.DATA };
        Cursor cursor = activity
                .managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

how to save image using preferences in android

Bitmap bitmap= BitmapFactory.decodeStream(stream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);  
byte[] b = baos.toByteArray();

String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
textEncode.setText(encodedImage);

SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit=shre.edit();
edit.putString("image_data",encodedImage);
edit.commit();

//and then, when retrieving, convert it back into bitmap:

SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
String previouslyEncodedImage = shre.getString("image_data", "");

if( !previouslyEncodedImage.equalsIgnoreCase("") ){
    byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
    Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
    image.setImageBitmap(bitmap);
}