Sunday, 14 September 2014

Flash Light Android App tutorial

Hi,
 This tutorial will explains you to implement Android Flash Light.

Following things are required to implement,

1. The device must have flash light facility.
2. Need to get CAMERA permission in AndroidMainifest.xml
3. Little bit knowledge in Android Development

Let us go with the following code example...................................

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

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


public class MainActivity extends Activity {

// flag to detect flash is on or off
private boolean isLighOn = false;
private Camera camera;
private TextView batteryTxt;
private ImageView cameraBtn;
Parameters params;

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

batteryTxt = (TextView) this.findViewById(R.id.textView1);
this.registerReceiver(this.mBatInfoReceiver, new           IntentFilter(Intent.ACTION_BATTERY_CHANGED));
cameraBtn = (ImageView) findViewById(R.id.buttonFlashlightappa);
Context context = this;
PackageManager pm = context.getPackageManager();

// if device support camera?
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return;
}
try {
camera = Camera.open();
params = camera.getParameters();
} catch (Exception e) {
System.out.println(e);
}
                // For flashlight button animation
final Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_in);
final Animation animation2 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_out);

cameraBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if (isLighOn) {
try {
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isLighOn = false;
cameraBtn.startAnimation(animation2);
cameraBtn.setImageDrawable(getResources().getDrawable(R.drawable.green));
cameraBtn.startAnimation(animation);
} catch (Exception e) {
System.out.println(e);
}

} else {
try {
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isLighOn = true;
cameraBtn.startAnimation(animation2);
cameraBtn.setImageDrawable(getResources().getDrawable(R.drawable.red));
cameraBtn.startAnimation(animation);
} catch (Exception e) {
System.out.println(e);
}
}
}
});
}

// get the level of battery in percentage
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context ctxt, Intent intent) {
try {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
batteryTxt.setText("Battery Level-" + String.valueOf(level)+ "%");
} catch (Exception e) {
System.out.println(e);
}
}
};
@Override
protected void onStop() {
super.onStop();
try {
if (camera != null) {
camera.release();
}
} catch (Exception e) {
System.out.println(e);
}
}

@Override
protected void onPause() {
super.onPause();
}
 
        // Detect light is on, if it is on, stop it when back button is pressed
public void onBackPressed() {
if (isLighOn) {
try {
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isLighOn = false;
} catch (Exception e) {
System.out.println(e);
}

}
finish();
}
}

Thursday, 11 September 2014

WEB SERVICE USING POST METHOD JSON FORMAT IN ANDROID…..!

Here, the post will explain about the web service using POST method in ANDROID.
1. Please find the link about POST method in Web API http://docs.oracle.com/cd/E19798-01/821-1841/giepu/index.html.
2. HTTP POST allows you to send data to the server in different formats such as XML, JSON or binary.
The following code will explain about the LOGIN API using POST. Here, we can pass our USERNAME and PASSWORD with the corresponding web server URL. Once we have posted we will be getting the response from the corresponding web server.
 --------------------------------------------------------------------------------------------
Request:
     List<NameValuePair> params = new ArrayList<NameValuePair>();
     params.clear();
     params.add(new BasicNameValuePair(“UserName”,”YOUR NAME”));
     params.add(new BasicNameValuePair(“UserPwd”, “YOUR PASSWORD”));
     new CallLoginAPI().execute();
Here, the Class CallLoginAPI() is used to perform the task inside AsyncTask. So it will not freeze the UI.
     public class CallLoginAPI extends AsyncTask<Void, Void, Integer> {
     @Override
     protected void onPreExecute() {
     // TODO Auto-generated method stub
   progressDialog = ProgressDialog.show(LoginActivity.this, “Logging in”, “Please Wait”);
     }
   @Override
     protected Integer doInBackground(Void… arg0) {
   // TODO Auto-generated method stub
      try {
                 CallWebURL();
           } catch (Exception e) { }
            return 0;
          }
     @SuppressLint(“NewApi”)
     protected void onPostExecute(Integer result) {
     super.onPostExecute(result);
     try
     {
     progressDialog.dismiss();
     if (result == 0) {
     System.out.println(“RESPONSE:” + RESPONSE);
     if (RESPONSE != null && RESPONSE.equalsIgnoreCase(“CONNECTION SUCCESS”)) {
          Toast.makeText(LoginActivity.this, ” Login Success “, Toast.LENGTH_LONG).show();     }
   else  
 {
          Toast.makeText(LoginActivity.this,” Invalid UserName and Password “, Toast.LENGTH_LONG).show();
     }
     } catch (Exception e) {
     System.out.println(e);
     }
     }

Android Custom Number Picker dialog box

Hi friends, here is the code to show NUMBER PICKER in the Custom Dialog Box for android.
--------------------------------------------------------------------------------------------------
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.main);
final String[] nums = new String[30];
for(int i=0; i<nums.length; i++) {
nums[i] = Integer.toString(i);
}
final NumberPicker np = (NumberPicker)dialog.findViewById(R.id.np);
np.setMaxValue(20);
np.setMinValue(0);
np.setWrapSelectorWheel(false);
np.setDisplayedValues(nums);
Button button = (Button)dialog.findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, “Selected value:”+nums[np.getValue()], Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
dialog.show();

XML layout  (main.xml)
-----------------------------------------------------------------------------------------
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="255dp"
    android:layout_height="match_parent"
    android:layout_gravity="top|center"
    android:background="#50CCCCCC"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:text="   "
            android:textAppearance="?android:attr/textAppearanceSmall" />

        <TextView
            android:id="@+id/expmin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/textView3"
            android:text=" Number picker "
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#3276b1"
            android:textStyle="bold|italic" />

        <NumberPicker
            android:id="@+id/np"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/expmin"
            android:layout_centerHorizontal="true" />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/np"
            android:layout_alignRight="@+id/np"
            android:layout_below="@+id/np"
            android:layout_marginTop="5dp"
            android:background="@drawable/button_selector"
            android:text="  OK  "
            android:textColor="#3276b1" />

    </RelativeLayout>

   <!--  <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="@drawable/button_selector"
        android:text="  OK  "
        android:textColor="#3276b1" /> -->

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="   "
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>