25 Nov 2012

Supporting Multiple Screens in Android.

This section provides an overview of Android's support for multiple screens.




In short you have make following Folder for images for All resolution.

               Folder Name                                                       Screen Resolution(W x H)

                  drawable-ldpi                                                                           240X320  
                  drawable-mdpi                                                                         320X480
                  drawable-hdpi                                                                          480X800/480X854
                  drawable- xhdpi(samsung S3)                                                 720X1280
                  drawable-xxhdpi(S4)                                                                1080 x 1920

Tablets Resolution:

                
//For 7 inch tablets
                  drawable-large-mdpi(7" tab)                                                   1024x600
                  drawable-large-hdpi(Nexus 7)                                                 720X1280
                  drawable-large-hdpi(Nexus 7C)                                               1200X1920 

//For 10 inch tablets

                  drawable-xlarge-mdpi(10.1" tab)                                             1280x800
                  drawable-xlarge-xhdpi(Nexus-10)                                            2560X1600
OR
                  drawable-sw600dp
                  drawable-sw720dp
         
More Ref Link :
I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.

Thank you :)

15 Oct 2012

Font compatibility for android devices and tablets.

Create Following all folders in Res folder of your Project.


       values-ldpi
       values-mdpi
       values-hdpi
       values-large-mdpi (This is for 7" tablets)
       values-xlarge (This is for 10" tablets)

       Now create xml file in each folder abs__dimens.xml and Give different text size in  <dimen></dimen>

       <?xml version="1.0" encoding="utf-8"?>
       <resources>
              <dimen name="txt_nm">10dip</dimen>
       </resources> 

       Now set this in to text view property-text size
       android:textSize="@dimen/txt_nm" />

       It will work fine for all Android devices and Tablets, Hop It will help you some one !

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)
       

10 Oct 2012

Video Recording example in Android

Hello friends, today i am going to post of Video recording in Android using surface view.

RecordVideoActivity.class 

import java.io.File;
import java.io.IOException;
import java.util.Date;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.Menu;
import android.view.SurfaceView;
import android.widget.Toast;

public class RecordVideoActivity extends Activity implements Callback
{
    @Override
    protected void onDestroy()
    {
        stopRecording();
        super.onDestroy();
    }

    private SurfaceHolder surfaceHolder;
    private SurfaceView surfaceView;
    public MediaRecorder mrec = new MediaRecorder();   
    private Camera mCamera;


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

        surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
        mCamera = Camera.open();
       
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
               
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {

        menu.add(0, 0, 0, "Start");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        if(item.getTitle().equals("Start"))
        {
            try {
               
                startRecording();
                item.setTitle("Stop");

            } catch (Exception e) {

                String message = e.getMessage();
                Log.i(null, "Problem " + message);
                mrec.release();
            }

        }
        else if(item.getTitle().equals("Stop"))
        {
            mrec.stop();
            mrec.release();
            mrec = null;
            item.setTitle("Start");
        }

        return super.onOptionsItemSelected(item);
    }

    protected void startRecording() throws IOException
    {
        if(mCamera==null)
            mCamera = Camera.open();
       
         String filename;
         String path;
       
         path= Environment.getExternalStorageDirectory().getAbsolutePath().toString();
        
         Date date=new Date();
         filename="/rec"+date.toString().replace(" ", "_").replace(":", "_")+".mp4";
        
         //create empty file it must use
         File file=new File(path,filename);
        
        mrec = new MediaRecorder();

        mCamera.lock();
        mCamera.unlock();

        // Please maintain sequence of following code.

        // If you change sequence it will not work.
        mrec.setCamera(mCamera);   
        mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mrec.setAudioSource(MediaRecorder.AudioSource.MIC);    
        mrec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mrec.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
        mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mrec.setPreviewDisplay(surfaceHolder.getSurface());
        mrec.setOutputFile(path+filename);
        mrec.prepare();
        mrec.start();

       
    }

    protected void stopRecording() {

        if(mrec!=null)
        {
            mrec.stop();
            mrec.release();
            mCamera.release();
            mCamera.lock();
        }
    }

    private void releaseMediaRecorder() {

        if (mrec != null) {
            mrec.reset(); // clear recorder configuration
            mrec.release(); // release the recorder object
        }
    }

    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.release(); // release the camera for other applications
            mCamera = null;
        }

    }

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

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {      

        if (mCamera != null) {
            Parameters params = mCamera.getParameters();
            mCamera.setParameters(params);
            Log.i("Surface", "Created");
        }
        else {
            Toast.makeText(getApplicationContext(), "Camera not available!",
                    Toast.LENGTH_LONG).show();

            finish();
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mCamera.stopPreview();
        mCamera.release();      

    }
}

activity_main.xml:


<SurfaceView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/surface_camera"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_centerInParent="true"
    android:layout_weight="1" >

</SurfaceView>


Permissions:

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

Download full source code from here VideoRecorderSampleCode

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

QR Code using Google Chart Tools APIs.

9 Oct 2012

Animation in android.

Hello Friends, today i am doing some important links for Animation in android.

Implement swiping page effect using GestureDetector and ViewFlipper:
Link: http://android-er.blogspot.in/2012/02/implement-swiping-page-effect-using.html

Animation using View Java Code:
Link: http://android-er.blogspot.in/2012/02/implament-animation-using-java-code.html

Animation using using Button event:
Link: http://android-er.blogspot.in/2012/02/bi-direction-viewflipper.html
Link: http://android-er.blogspot.in/2012/02/apply-animation-on-button.html

Various effect of interpolator in Android Animation:
Link: http://android-er.blogspot.in/2012/02/various-effect-of-interpolator-in.html

Animate Fade In/Fade Out by changing Alpha:
Link: http://android-er.blogspot.in/2012/02/animate-fade-infade-out-by-changing.html

 Frame animation with AnimationDrawable:
 Link: http://android-er.blogspot.in/2012/01/create-frame-animation-with.html

Sliding drawer in android:
http://www.coderzheaven.com/2011/12/01/slidingdrawer-in-android-a-simple-example/
http://androidtrainningcenter.blogspot.in/2012/08/android-sliding-drawer-example.html

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.

Thank you :)

Signed APK for Android Application.

http://android-er.blogspot.in/2012/02/generate-signed-apk-for-android.html


I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

8 Oct 2012

Video Control play time in Android.

Weather App in Android.

http://android-er.blogspot.in/2012/03/google-weather-app.html


I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

Get current location | latitude and longitude in Android.

EXAMPLE : 1 


Step 1: Add below dependency into your project.
implementation 'com.google.android.gms:play-services-location:18.0.0'
Step 2: Implement coding for the runtime permission for the location.
Step 3: Add below permission in to the android manifest.
<uses-permission android:name = "android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />

 Step 4: Below is the code spinet to get current location from the mobile.

class LocationHelper
{
    private val TAG = this.javaClass.name
    private var cancellationTokenSource = CancellationTokenSource()    

    fun getLocation(activity: Activity)
    {
        val fusedLocationClient = LocationServices.getFusedLocationProviderClient(activity)
        if (ActivityCompat.checkSelfPermission(activity,
     Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(activity,
     Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            return
        }

        val currentLocationTask: Task<Location> =  fusedLocationClient.getCurrentLocation(
PRIORITY_HIGH_ACCURACY, cancellationTokenSource.token)

        currentLocationTask.addOnCompleteListener { task: Task<Location> ->
            if (task.isSuccessful && task.result != null)
            {
                val result: Location = task.result                
                Log.i(TAG,"getLocation : (success): ${result.latitude}, ${result.longitude}")
            }
            else
            {
                val exception = task.exception
                Log.i(TAG,"getLocation : "+exception?.message!!)
            }
        }
    }
}

 Step 5: Call method.

LocationHelper.getCurrentLocation(activity)

EXAMPLE : 2


Here is one example which try to find location using GPS , if your GPS not available then try to use network for find location. GPS or Network not enable then it will ask user to Enable Gps/network Setting.





MyLocation.java

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class MyLocation extends Service implements LocationListener {

       private final Context mContext;

       // flag for GPS status
       boolean isGPSEnabled = false;

       // flag for network status
       boolean isNetworkEnabled = false;

       // flag for GPS status
       boolean isLocationAvailable = false;

       Location location// location
       double latitude// latitude
       double longitude// longitude

       // The minimum distance to change Updates in meters
       private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

       // The minimum time between updates in milliseconds
       private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

       // Declaring a Location Manager
       protected LocationManager locationManager;

       public MyLocation(Context context) {
              this.mContext = context;
              getLocation();
       }

       public Location getLocation() {
              try {
                     locationManager = (LocationManager) mContext
                                  .getSystemService(LOCATION_SERVICE);

                     // getting GPS status
                     isGPSEnabled = locationManager
                                 .isProviderEnabled(LocationManager.GPS_PROVIDER);

                     // getting network status
                     isNetworkEnabled = locationManager
                                 .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

                     if (!isGPSEnabled && !isNetworkEnabled) {
                           // no network provider is enabled
                     } else {
                           this.isLocationAvailable = true;
                           if (isNetworkEnabled) {
                                  locationManager.requestLocationUpdates(
                                               LocationManager.NETWORK_PROVIDER,
                                                MIN_TIME_BW_UPDATES,
                                               MIN_DISTANCE_CHANGE_FOR_UPDATESthis);
                                  Log.d("Network""Network");
                                  if (locationManager != null) {
                                         location = locationManager
                                                      .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                                         if (location != null) {
                                                latitude =location.getLatitude();
                                                longitude =location.getLongitude();
                                         }
                                  }
                           }
                           // if GPS Enabled get lat/long using GPS Services
                           if (isGPSEnabled) {
                                  if (location == null) {
                                        locationManager.requestLocationUpdates(
                                                      LocationManager.GPS_PROVIDER,
                                                       MIN_TIME_BW_UPDATES,
                                                      MIN_DISTANCE_CHANGE_FOR_UPDATESthis);
                                         Log.d("GPS Enabled""GPS Enabled");
                                         if (locationManager != null) {
                                                location = locationManager
                                                             .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                                if (location != null) {
                                                       latitude =location.getLatitude();
                                                       longitude =location.getLongitude();
                                                }
                                         }
                                  }
                           }
                     }

              } catch (Exception e) {
                     e.printStackTrace();
              }

              return location;
       }

       /**
        * Stop using GPS listener Calling this function will stop using GPS in your
        * app
        * */
       public void stopUsingGPS() {
              if (locationManager != null) {
                     locationManager.removeUpdates(MyLocation.this);
              }
       }

       /**
        * Function to get latitude
        * */
       public double getLatitude() {
              if (location != null) {
                     latitude = location.getLatitude();
              }

              // return latitude
              return latitude;
       }

       /**
        * Function to get longitude
        * */
       public double getLongitude() {
              if (location != null) {
                     longitude = location.getLongitude();
              }

              // return longitude
              return longitude;
       }

       /**
        * Function to check GPS/wifi enabled
        *
        * @return boolean
        * */
       public boolean isLocationAvailable() {
              return this.isLocationAvailable;
       }

       /**
        * Function to show settings alert dialog On pressing Settings button will
        * lauch Settings Options
        * */
       public void showSettingsAlert() {
              AlertDialog.Builder alertDialog = newAlertDialog.Builder(mContext);

              // Setting Dialog Title
              alertDialog.setTitle("GPS is settings");

              // Setting Dialog Message
              alertDialog
                           .setMessage("GPS is not enabled. Do you want to go to settings menu?");

              // On pressing Settings button
              alertDialog.setPositiveButton("Settings",
                           new DialogInterface.OnClickListener() {
                                  public void onClick(DialogInterface dialog, int which) {
                                         Intent intent = new Intent(
                                                      Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                         mContext.startActivity(intent);
                                  }
                           });

              // on pressing cancel button
              alertDialog.setNegativeButton("Cancel",
                           new DialogInterface.OnClickListener() {
                                  public void onClick(DialogInterface dialog, int which) {
                                         dialog.cancel();
                                  }
                           });

              // Showing Alert Message
              alertDialog.show();
       }

       @Override
       public void onLocationChanged(Location location) {
       }

       @Override
       public void onProviderDisabled(String provider) {
       }

       @Override
       public void onProviderEnabled(String provider) {
       }

       @Override
       public void onStatusChanged(String provider, int status, Bundle extras) {
       }

       @Override
       public IBinder onBind(Intent arg0) {
              return null;
       }

}


MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
       // MyLocation class
       MyLocation myLocation;

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

              Button mylocationBtn = (Button) findViewById(R.id.MyLatLongBtn);
              mylocationBtn.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View v) {
                           // TODO Auto-generated method stub

                           TextView latitudeTv = (TextView) findViewById(R.id.latitudeTV);
                           TextView longitudeTv = (TextView) findViewById(R.id.longitudeTv);

                           // create class object
                           myLocation = new MyLocation(MainActivity.this);

                           // check if GPS enabled
                           if (myLocation.isLocationAvailable()) {

                                  Double latitude =myLocation.getLatitude();
                                  Double longitude =myLocation.getLongitude();

                                  latitudeTv.setText(latitude.toString());
                                 longitudeTv.setText(longitude.toString());
                           } else {
                                  // can't get location
                                  // GPS or Network is not enabled
                                  // Ask user to enable GPS/network in settings
                                  myLocation.showSettingsAlert();
                           }

                     }
              });

       }
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/bgimage" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="21dp"
        android:text="Longitude"
        android:textColor="@android:color/white"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/latitudeTV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView1"
        android:layout_alignBottom="@+id/textView1"
        android:layout_alignParentRight="true"
        android:text="00"
        android:textColor="@android:color/white"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/longitudeTv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView2"
        android:layout_alignBottom="@+id/textView2"
        android:layout_alignLeft="@+id/latitudeTV"
        android:text="00"
        android:textColor="@android:color/white"
        android:textSize="18sp" />

    <Button
        android:id="@+id/MyLatLongBtn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:text="MyLatLong"
        android:textColor="@android:color/white" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/textView2"
        android:layout_marginTop="50dp"
        android:text="Latitude"
        android:textColor="@android:color/white"
        android:textSize="18sp" />

</RelativeLayout>

Permition in manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.itdeveloper.khurram"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

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

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


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.itdeveloper.khurram.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>
    </application>

</manifest>


I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.

Thank you :)