Ad

Showing posts with label Camera. Show all posts
Showing posts with label Camera. Show all posts

Monday, January 5, 2015

Android custom camera

Android custom camera library.


 Every manufacture of Android devices have a different approach to the camera and the worst part is: there is no guarantee that if you send your custom settings to the camera - the software will take them in consideration.
For example:
  1. Samsung device could care less about the resolution that we wanted - it always took the photos at the higher resolution.
  2. HTC devices would crop the photos. So if your device says that you have a a camera with a 5Mpx sensor, in reality the camera will produce a 4,4Mpx photo.
This is why i created the custom camera app. While developing i had to reinvent the wheal many times for different stuff since Google dose not provide basic functionality that Apple dose in its iOS. A good example is the accelerometer. In both system you can get the raw data, but Apple gives you something more. You can get the orientation of the device if this is all what you need.


Sunday, November 17, 2013

Android Enable GPS (Check and prompt user to enable GPS)

GPS Location

To check if the GPS have been enabled or not, the following code can be used:

String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

If it's empty, means the GPS have not been enabled. You can start activity with intentSettings.ACTION_SECURITY_SETTINGS, to switch to GPS setting page.




Activity

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.Toast;

public class AndroidEnableGPS extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
     
       CheckEnableGPS();
   }
 
   private void CheckEnableGPS(){
    String provider = Settings.Secure.getString(getContentResolver(),
      Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
       if(!provider.equals("")){
           //GPS Enabled
        Toast.makeText(AndroidEnableGPS.this, "GPS Enabled: " + provider,
          Toast.LENGTH_LONG).show();
       }else{
        Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
           startActivity(intent);
       }

   }
}


Android Internal and External storage

  • Android Internal Storage
    •  Internal storage are private to your application and other applications cannot access them (nor can the user).
    •  When the user uninstalls your application, these files are removed.
  •  Android External Storage
    •  External storage such as SD card can also store application data.
    •  There's no security enforced upon files you save to the external storage.
    •  All applications can read and write files placed on the external storage and the user can remove them.
    •  You need Read and Write permission in External Storage
In this example we are going to save data from an EditText to both Internal Storage and External Storage, and then try to get the data back from the respective storage places.

 FileOutputStream :For save Data
 FileInputStream  :For Display data



Layout - activity_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:text="Storage Demo" />

    <EditText
        android:id="@+id/InputText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:gravity="top|left"
        android:inputType="textMultiLine"
        android:lines="5"
        android:minLines="2"
        android:text="Internal and External Storage" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/InternalStorageSave"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Internal Storage(Save)" />

    <Button
        android:id="@+id/InternalStorageGet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Internal Storage(Display)" />

    <Button
        android:id="@+id/ExternalStorageSave"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="External Storage(Save)" />

    <Button
        android:id="@+id/ExternalStorageGet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="External Storage(Displays)" />

    <TextView
        android:id="@+id/responseText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>

Activity - MainActivity.java

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;



public class MainActivity extends Activity implements OnClickListener {

    private String filename = "StorageFile.txt";
    private String filepath = "FileStorage";
    File myInternalFile;
    File myExternalFile;

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

        ContextWrapper contextWrapper = new ContextWrapper(
                getApplicationContext());
        File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
        myInternalFile = new File(directory, filename);

        Button saveToInternalStorage = (Button) findViewById(R.id.InternalStorageSave);
        saveToInternalStorage.setOnClickListener(this);

        Button readFromInternalStorage = (Button) findViewById(R.id.InternalStorageGet);
        readFromInternalStorage.setOnClickListener(this);

        Button saveToExternalStorage = (Button) findViewById(R.id.ExternalStorageSave);
        saveToExternalStorage.setOnClickListener(this);

        Button readFromExternalStorage = (Button) findViewById(R.id.ExternalStorageGet);
        readFromExternalStorage.setOnClickListener(this);

        // check if external storage is available and not read only
        if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
            saveToExternalStorage.setEnabled(false);
        } else {
            myExternalFile = new File(getExternalFilesDir(filepath), filename);
        }

    }

    public void onClick(View v) {

        EditText myInputText = (EditText) findViewById(R.id.InputText);
        TextView responseText = (TextView) findViewById(R.id.responseText);
        String myData = "";

        switch (v.getId()) {
        case R.id.InternalStorageSave:
            try {
                FileOutputStream fos = new FileOutputStream(myInternalFile); // save
                fos.write(myInputText.getText().toString().getBytes());
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            myInputText.setText("");
            responseText.setText("Saved to Internal Storage.(StorageFile.txt)");
            break;

        case R.id.InternalStorageGet:
            try {
                FileInputStream fis = new FileInputStream(myInternalFile); // display
                DataInputStream in = new DataInputStream(fis);
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(in));
                String strLine;
                while ((strLine = br.readLine()) != null) {
                    myData = myData + strLine;
                }
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            myInputText.setText(myData);
            responseText
                    .setText("Data retrieved from Internal Storage.(StorageFile.txt)");

            break;

        case R.id.ExternalStorageSave:
            try {
                FileOutputStream fos = new FileOutputStream(myExternalFile);
                fos.write(myInputText.getText().toString().getBytes());
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            myInputText.setText("");
            responseText.setText("Saved to External Storage.(StorageFile.txt)");
            break;

        case R.id.ExternalStorageGet:
            try {
                FileInputStream fis = new FileInputStream(myExternalFile);
                DataInputStream in = new DataInputStream(fis);
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(in));
                String strLine;
                while ((strLine = br.readLine()) != null) {
                    myData = myData + strLine;
                }
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            myInputText.setText(myData);
            responseText
                    .setText("Data retrieved from Internal Storage.(StorageFile.txt)");
            break;

        }
    }

    private static boolean isExternalStorageReadOnly() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
            return true;
        }
        return false;
    }

    private static boolean isExternalStorageAvailable() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
            return true;
        }
        return false;
    }

}

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


Tuesday, March 12, 2013

Android Phone call history/log programmatically


activity_main.xml

<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/call"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

</RelativeLayout>

MainActivity.java

public class MainActivity extends Activity {

    private static final int MISSED_CALL_TYPE = 0;
    private TextView txtcall;

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

        txtcall = (TextView) findViewById(R.id.call);

        StringBuffer sb = new StringBuffer();
        Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null,
                null, null, null);
        int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
        int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
        int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
        int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
        sb.append("Call Details :");
        while (managedCursor.moveToNext()) {
            String phNumber = managedCursor.getString(number);
            String callType = managedCursor.getString(type);
            String callDate = managedCursor.getString(date);
            Date callDayTime = new Date(Long.valueOf(callDate));
            String callDuration = managedCursor.getString(duration);
            String dir = null;
            int dircode = Integer.parseInt(callType);
            switch (dircode) {

            case CallLog.Calls.OUTGOING_TYPE:
                dir = "OUTGOING";
                break;

            case CallLog.Calls.INCOMING_TYPE:
                dir = "INCOMING";
                break;

            case CallLog.Calls.MISSED_TYPE:
                dir = "MISSED";
                break;
            }
            sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
                    + dir + " \nCall Date:--- " + callDayTime
                    + " \nCall duration in sec :--- " + callDuration);
            sb.append("\n----------------------------------");
        }
        managedCursor.close();
        txtcall.setText(sb);
    }

    @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;
    }

}

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



Friday, December 21, 2012

Android Turn ON wifi programmatically


Android Turn ON wifi  programmatically

Coding for Enable WIFI programmatically.
Activity.class

import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.widget.TextView;

public class WifiEnableActivity extends Activity {
    /** Called when the activity is first created. */
    private WifiManager wifiManager; 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); 
       TextView text = (TextView)findViewById(R.id.txtWiFi);
          wifiManager.setWifiEnabled(true); 
          if(wifiManager.isWifiEnabled()){
              text.setText("Wifi State Enabled");
          }
        
    }
}
Then  some permission and user feature required in manifest file.
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission> 
    <uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"></uses-permission> 
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission> 
    <uses-feature android:name="android.hardware.wifi.direct" />
    <uses-permission    android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>

Download Source Code

Thursday, December 20, 2012

Android Toast notification show Different Gravity


Toast notify we can show in different gravity like "TOP", "RIGHT", "LEFT", "BOTTOM",etc.

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
       
        Toast t = Toast.makeText(MainActivity.this, "TOP | RIGHT", Toast.LENGTH_LONG);
        t.setGravity(Gravity.TOP|Gravity.RIGHT, 0, 0);
        t.show();
       
        t = Toast.makeText(MainActivity.this, "CENTER", Toast.LENGTH_LONG);
        t.setGravity(Gravity.CENTER, 0, 0);
        t.show();
       
        t = Toast.makeText(MainActivity.this, "BOTTOM | LEFT", Toast.LENGTH_LONG);
        t.setGravity(Gravity.BOTTOM|Gravity.LEFT, 0, 0);
        t.show();
       
        t = Toast.makeText(MainActivity.this, "CENTER | LEFT", Toast.LENGTH_LONG);
        t.setGravity(Gravity.CENTER|Gravity.LEFT, 0, 0);
        t.show();
    
    }
   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}


Monday, November 26, 2012

Android Capture photo using camera


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

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="photo" >
    </Button>

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" >
    </ImageView>

</LinearLayout>

MainActivity.java

public class MainActivity  extends Activity {
    private static final int CAMERA_REQUEST = 1888;
    private ImageView imageView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.imageView = (ImageView)this.findViewById(R.id.imageView1);
        Button photoButton = (Button) this.findViewById(R.id.button1);
        photoButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraIntent, CAMERA_REQUEST);
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) { 
            Bitmap photo = (Bitmap) data.getExtras().get("data");
            imageView.setImageBitmap(photo);
        } 
    }
}

AndroidManifest.xml

<uses-feature android:name="android.hardware.camera"></uses-feature>