Monday, May 20, 2013

Camera Video Capture And Save On SDCard - Android Example


XML FILE : AndroidManifest.xml

 



<?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.androidexample.camera"
      android:versionCode="1"
      android:versionName="1.0">
     
    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="17" />
    <application android:icon="@drawable/icon"
        android:label="@string/app_name">
        <activity android:name="com.androidexample.camera.VideocameraActivity"
                  android:screenOrientation="portrait"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
     
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!-- For android.media.audiofx.Visualizer -->
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
        <!-- We will request access to the camera, saying we require a camera
         of some sort but not one with autofocus capability. -->
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
     
</manifest>


JAVA FILE : VideocameraActivity.php

 

 1.  Opening android phone inbuild camera by camera intent.
  2.  Capture photo and again return on VideocameraActivity.java onActivityResult method.
  3.  Inside onActivityResult method getting captured video saved path and showing path on activity.

package com.valkeshexample.camera;
import java.io.File;
import java.text.SimpleDateFormat;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class VideocameraActivity extends Activity {
     
    private Uri fileUri;
    public static final int MEDIA_TYPE_VIDEO = 2;
    private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
    public static VideocameraActivity ActivityContext =null;
    public static TextView val_output;
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ActivityContext = this;
         
        Button buttonRecording = (Button)findViewById(R.id.recording);
        val_output = (TextView)findViewById(R.id.val_output);
         
        buttonRecording.setOnClickListener(new Button.OnClickListener(){
            @Override
            public void onClick(View arg0) {
                 
                // create new Intentwith with Standard Intent action that can be
                // sent to have the camera application capture an video and return it.
                Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                // create a file to save the video
                fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
                 
                // set the image file name 
                intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); 
                 
                // set the video image quality to high
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                // start the Video Capture Intent
                startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
                 
            }});
         
         
    }
     
    /** Create a file Uri for saving an image or video */
    private static Uri getOutputMediaFileUri(int type){
         
          return Uri.fromFile(getOutputMediaFile(type));
    }
    /** Create a File for saving an image or video */
    private static File getOutputMediaFile(int type){
         
        // Check that the SDCard is mounted
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                  Environment.DIRECTORY_PICTURES), "MyCameraVideo");
         
         
        // Create the storage directory(MyCameraVideo) if it does not exist
        if (! mediaStorageDir.exists()){
             
            if (! mediaStorageDir.mkdirs()){
                 
                val_output.setText("Failed to create directory MyCameraVideo.");
                 
                Toast.makeText(ActivityContext, "Failed to create directory MyCameraVideo.",
                        Toast.LENGTH_LONG).show();
                 
                Log.d("MyCameraVideo", "Failed to create directory MyCameraVideo.");
                return null;
            }
        }
         
        // Create a media file name
         
        // For unique file name appending current timeStamp with file name
        java.util.Date date= new java.util.Date();
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                             .format(date.getTime());
         
        File mediaFile;
         
        if(type == MEDIA_TYPE_VIDEO) {
             
            // For unique video file name appending current timeStamp with file name
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
            "VID_"+ timeStamp + ".mp4");
             
        } else {
            return null;
        }
        return mediaFile;
    }
     
     
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
         
        // After camera screen this code will excuted
         
        if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
             
            if (resultCode == RESULT_OK) {
                 
                val_output.setText("Video File : " +data.getData());
                 
                // Video captured and saved to fileUri specified in the Intent
                Toast.makeText(this, "Video saved to:
" +
                         data.getData(), Toast.LENGTH_LONG).show();
                 
            } else if (resultCode == RESULT_CANCELED) {
                 
                val_output.setText("User cancelled the video capture.");
                 
                // User cancelled the video capture
                Toast.makeText(this, "User cancelled the video capture.",
                        Toast.LENGTH_LONG).show();
                 
            } else {
                 
                val_output.setText("Video capture failed.");
                 
                // Video capture failed, advise user
                Toast.makeText(this, "Video capture failed.",
                        Toast.LENGTH_LONG).show();
            }
        }
    }
     
}

XML FILE : main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
      <Button
            android:id="@+id/recording"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Capture Video"
            />
   <TextView 
    android:id="@+id/val_output"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello"
     
    />
</LinearLayout>
 
 

 

Sunday, May 12, 2013

Open video or audio with default application using Intents

 
 
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File("/sdcard/test.mp4");
intent.setDataAndType(Uri.fromFile(file), "video/*");
startActivity(intent); 
 
 
 
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File("/sdcard/test.mp3");
intent.setDataAndType(Uri.fromFile(file), "audio/*");
startActivity(intent); 

Wednesday, May 8, 2013

programmatically-set-weight-for-button in android

You are create when Dynamically button then set weight without use xml.
then use it this code
  
LinearLayout.LayoutParams size = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
size.weight = 1; 
 
Button btn = new Button(MainActivity.this);  
btn.setLayoutParams(size);
 
 
You have to use TableLayout.LayoutParams
TextView tv = new TextView(v.getContext());
tv.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
LayoutParams.WRAP_CONTENT, 1f));  

Tuesday, May 7, 2013

WIFI Connection in Android

Check WIFI is ON Or OFF In your android application 
First  to  add This line in Your AndroidManifest.xml
android.permission.ACCESS_NETWORK_STATE  
And then Use This Code: 
Public Boolean checkWifiConnection(){ 
ConnectivityManager connManager =   
(ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = 
connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {return true;}
else{return false; }}
 
  OR Next Solution
  

Detect Wifi ON/OFF state 

To detect Android Wifi ON/OFF (Enable/Disable) state, we can implement a BroadcastReceiver to register with the intent WifiManager.WIFI_STATE_CHANGED_ACTION. IN the BroadcastReceiver, the Wifi state can be retrieved using the code intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN).


package com.exercise.AndroidWifiStateChangedDetect;

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

public class AndroidWifiStateChangedDetect extends Activity {

TextView WifiState;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      WifiState = (TextView)findViewById(R.id.wifistate);
    
      this.registerReceiver(this.WifiStateChangedReceiver,
              new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
  }

  private BroadcastReceiver WifiStateChangedReceiver
  = new BroadcastReceiver(){

 @Override
 public void onReceive(Context context, Intent intent) {
  // TODO Auto-generated method stub
 
  int extraWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE ,
    WifiManager.WIFI_STATE_UNKNOWN);
 
  switch(extraWifiState){
  case WifiManager.WIFI_STATE_DISABLED:
   WifiState.setText("WIFI STATE DISABLED");
   break;
  case WifiManager.WIFI_STATE_DISABLING:
   WifiState.setText("WIFI STATE DISABLING");
   break;
  case WifiManager.WIFI_STATE_ENABLED:
   WifiState.setText("WIFI STATE ENABLED");
   break;
  case WifiManager.WIFI_STATE_ENABLING:
   WifiState.setText("WIFI STATE ENABLING");
   break;
  case WifiManager.WIFI_STATE_UNKNOWN:
   WifiState.setText("WIFI STATE UNKNOWN");
   break;
  }
 
 }};
}

 

Update a Database in Android Application

Update a Database in Android Application

When you need to modify a subset of your database values, use the update() method.
Updating the table combines the content values syntax of insert() with the where syntax of delete().


SQLiteDatabase db = mDbHelper.getReadableDatabase();
// New value for one column
ContentValues values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, title);
// Which row to update, based on the ID
String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
String[] selectionArgs = { String.valueOf(rowId) };
int count = db.update(
    FeedReaderDbHelper.FeedEntry.TABLE_NAME,
    values,
    selection,
    selectionArgs);