Open top menu





Example- Explain how to ON and OFF Flash Light in android device programmatically.

Step 1- Add below permission in manifest file.

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

.............................................................................................

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"
    android:background="@drawable/gradient"
    tools:context=".MainActivity" >

    <ImageButton
       
android:id="@+id/btnSwitch"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dip"
        android:src="@drawable/switch_on_icon"
        android:background="@null"
        android:scaleType="fitXY"
        android:contentDescription="@null"
        />
</RelativeLayout>


.............................................................................................

MainActivity.Java
.............................................................................................

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;

public class MainActivity extends AppCompatActivity {
    ImageButton btnSwitch;

    private Camera camera;
    private boolean isFlashOn;
    private boolean hasFlash;
    Parameters params;
    MediaPlayer mp;

    @Override
   
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);

        
        hasFlash = getApplicationContext().getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
        if (!hasFlash) {

            AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
            alert.setTitle("Error");
            alert.setMessage("device doesn't support flash light!");
            alert.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            alert.show();
            return;
        }
       
        getCamera();
       
        toggleButtonImage();
       
        btnSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
           
public void onClick(View v) {
                if (isFlashOn) {
                    turnOffFlash();
                } else {
                    turnOnFlash();
                }
            }
        });
    }
    private void getCamera() {
        if (camera == null) {
            try {
                camera = Camera.open();
                params = camera.getParameters();
            } catch (RuntimeException e) {

            }
        }
    }
   
    private void turnOnFlash() {
        if (!isFlashOn) {
            btnSwitch.setBackgroundResource(R.drawable.switch_on_icon);
            if (camera == null || params == null) {
                return;
            }
           
            params = camera.getParameters();
            params.setFlashMode(Parameters.FLASH_MODE_TORCH);
            camera.setParameters(params);
            camera.startPreview();
            isFlashOn = true;
            toggleButtonImage();
        }

    }
   
    private void turnOffFlash() {
        if (isFlashOn) {
            if (camera == null || params == null) {
                return;
            }
            params = camera.getParameters();
            params.setFlashMode(Parameters.FLASH_MODE_OFF);
            camera.setParameters(params);
            camera.stopPreview();
            isFlashOn = false;
            toggleButtonImage();
        }
    }
   
    private void toggleButtonImage(){
        if(isFlashOn){
            btnSwitch.setImageResource(R.drawable.switch_on_icon);
        }else{
            btnSwitch.setImageResource(R.drawable.switch_off_icon);
        }
    }

    @Override
   
protected void onDestroy() {
        super.onDestroy();
    }

    @Override
   
protected void onPause() {
        super.onPause();
        turnOffFlash();
    }

    @Override
   
protected void onRestart() {
        super.onRestart();
    }

     

    @Override
   
protected void onStart() {
        super.onStart();
        getCamera();
    }

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

 ............................................................................................




Read more






 Android Example –How to Vibrate android device programmatically?

Step 1:- Add bellow permission in your manifest file.
<uses-permission android:name="android.permission.VIBRATE"/>

Step 2: Get Vibrate System Service.
Vibrator vibrate = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

Step 3: Set Vibrate  Time period in milliseconds and Time Pattern. Time Pattern means like start/stope vibration.
vibrate.vibrate(300);//in millisecond.

Pattern
long pattern[] = {60,120,180,240,300,360,420,480};
vibrate.vibrate(pattern,1);

 .................................................................................................................................................................

 activity_main.xml
.................................................................................................................................................................
xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:tools="http://schemas.android.com/tools"
   
android:id="@+id/activity_main"
    
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
android:gravity="center"
  
android:orientation="vertical">

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

    <
Button
       
android:id="@+id/btn_start"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_below="@+id/textView1"
       
android:text="Vibrate Start"
       
android:layout_margin="20dp"/>
    <
Button
       
android:id="@+id/btn_stope"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_below="@+id/textView1"
       
android:text="Vibrate Stope"
       
android:layout_margin="20dp"/>

</
LinearLayout>
.................................................................................................................................................................



MainActivity.java
.................................................................................................................................................................

 

import android.content.Context;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView
text;
    Vibrator
vibrate;
    Button
btn_start,btn_stope;

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
       
text = (TextView) findViewById(R.id.textView1);
       
btn_start = (Button) findViewById(R.id.btn_start);
       
btn_stope = (Button) findViewById(R.id.btn_stope);

       
vibrate = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
       
btn_start.setOnClickListener(new View.OnClickListener() {

           
@Override
           
public void onClick(View v) {
               
long pattern[] = {60,120,180,240,300,360,420,480};
               
vibrate.vibrate(pattern,1);
               
//vibrate.vibrate(300);
               
text.setText("Vibrate Start...");

            }
        });
       
btn_stope.setOnClickListener(new View.OnClickListener() {

           
@Override
           
public void onClick(View v) {
               
vibrate.cancel();
               
text.setText("Vibrate Stope...");


            }
        });
    }

}

.................................................................................................................................................................


Read more



Example- How to Support Different Languages in Android ?



Exaplain-Create Loacale Directories (values folder) and string file .  e.g we are used Indonesian language so create values-in folder show below Image.
...................................................................................................................................................................




...................................................................................................................................................................

Activity_main.xml.
...................................................................................................................................................................
xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:tools="http://schemas.android.com/tools"
   
android:id="@+id/activity_main"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
android:paddingBottom="@dimen/activity_vertical_margin"
   
android:paddingLeft="@dimen/activity_horizontal_margin"
   
android:paddingRight="@dimen/activity_horizontal_margin"
   
android:paddingTop="@dimen/activity_vertical_margin"
   
>

    <
RadioGroup
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:orientation="horizontal"
       
android:id="@+id/rd_group"
       
android:layout_marginLeft="140dp">

        <
RadioButton
           
android:layout_width="wrap_content"
           
android:layout_height="wrap_content"
           
android:text="English"
           
android:layout_gravity="right|top"
           
android:id="@+id/enlish"
           
android:onClick="onRadioButtonClicked"
           
android:checked="true"/>

        <
RadioButton
           
android:layout_width="wrap_content"
           
android:layout_height="wrap_content"
           
android:text="Indonesian"
           
android:id="@+id/indonesia"
            
android:onClick="onRadioButtonClicked"
           
android:layout_marginLeft="12dp"
           
android:checked="false"
           
/>
    </
RadioGroup>

    <
EditText
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:inputType="textPersonName"
       
android:ems="10"
       
android:layout_below="@+id/rd_group"
       
android:layout_centerHorizontal="true"
       
android:layout_marginTop="67dp"
       
android:id="@+id/editText" />

    <
EditText
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:inputType="textPersonName"
       
android:ems="10"
       
android:layout_below="@+id/editText"
       
android:layout_alignLeft="@+id/editText"
       
android:layout_alignStart="@+id/editText"
       
android:layout_marginTop="33dp"
       
android:id="@+id/editText2" />

    <
Button
       
android:text="Button"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_below="@+id/editText2"
       
android:layout_marginTop="88dp"
       
android:id="@+id/button"
       
android:layout_alignRight="@+id/editText2"
       
android:layout_alignEnd="@+id/editText2"
       
android:layout_alignLeft="@+id/editText2"
       
android:layout_alignStart="@+id/editText2" />

    <
TextView
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_below="@+id/editText2"
       
android:layout_alignRight="@+id/button"
       
android:layout_alignEnd="@+id/button"
       
android:layout_marginRight="12dp"
       
android:layout_marginEnd="12dp"
       
android:layout_marginTop="42dp"
       
android:id="@+id/textView" />

    <
TextView
       
android:text="Android Beginner point"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:textColor="#0f8c0f"
       
android:textStyle="bold"
       
android:textSize="18dp"
       
android:layout_alignParentBottom="true"
       
android:layout_centerHorizontal="true"
       
android:id="@+id/textView2" />


</
RelativeLayout>
...................................................................................................................................................................



LocaleHelper.java
................................................................................................................................................................... 

public class LocaleHelper {

   
private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

   
public static void onCreate(Context context) {
        String lang = getPersistedData(context, Locale.getDefault().getLanguage());
        setLocale(context, lang);
    }

   
public static void onCreate(Context context, String defaultLanguage) {
        String lang = getPersistedData(context, defaultLanguage);
        setLocale(context, lang);
    }

   
public static String getLanguage(Context context) {
       
return getPersistedData(context, Locale.getDefault().getLanguage());
    }

   
public static void setLocale(Context context, String language) {
        persist(context, language);
        updateResources(context, language);
    }

   
private static String getPersistedData(Context context, String defaultLanguage) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
       
return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
    }

   
private static void persist(Context context, String language) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();

        editor.putString(
SELECTED_LANGUAGE, language);
        editor.apply();
    }

   
private static void updateResources(Context context, String language) {
        Locale locale =
new Locale(language);
        Locale.setDefault(locale);
        Resources resources = context.getResources();
        Configuration configuration = resources.getConfiguration();
        configuration.
locale = locale;
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
    }
}

...................................................................................................................................................................


MainActivity.java
...................................................................................................................................................................


public class MainActivity extends AppCompatActivity {
    Resources
resources;
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
        LocaleHelper.setLocale(
this, "en");
        UpdateView();

    }

   
public void UpdateView(){
       
resources = getResources();
        ((EditText)findViewById(R.id.
editText)).setHint(resources.getString(R.string.UserId));
        ((EditText)findViewById(R.id.
editText2)).setHint(resources.getString(R.string.UserPassword));
        ((TextView)findViewById(R.id.
textView)).setText(resources.getString(R.string.fogetpass));
        ((Button)findViewById(R.id.
button)).setText(resources.getString(R.string.Userlogin));
    }

   
public void onRadioButtonClicked(View view) {
       
// Is the button now checked?
       
boolean checked = ((RadioButton) view).isChecked();

       
// Check which radio button was clicked
       
switch (view.getId()) {
           
case R.id.enlish:
               
if (checked)

                LocaleHelper.setLocale(
this, "en");
                UpdateView();

               
break;
           
case R.id.indonesia:
               
if (checked)
                LocaleHelper.setLocale(
this, "in");
                UpdateView();

               
break;
        }
    }
}
...................................................................................................................................................................


Read more