Thursday 26 March 2015

Check orientation on Android phone

Make a class and paste the function


public String getRotation(Context context){
    final int rotation = ((WindowManager) context.getSystemService 
           (Context.WINDOW_SERVICE)).getDefaultDisplay().getOrientation();
           switch (rotation) {
            case Surface.ROTATION_0:
                return "portrait";
            case Surface.ROTATION_90:
                return "landscape";
            case Surface.ROTATION_180:
                return "reverse portrait";
            default:
                return "reverse landscape";
            }
        }
 
This function will return the current phone orientation value string .



Turn on/off camera flash light programmatically in Android

Step 1)
Add the below permission to manifest.xml 
<uses-permission android:name="android.permission.CAMERA" />  
<uses-permission android:name="android.permission.FLASHLIGHT"/>  

Step 2)
Check programmatically the availability of flashlight in device .

context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
It returns true if flash is available .

Step 3)
Turn on camera flash light LED.
Camera cam = Camera.open();     
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
 
Step 4)
Turn off camera flash light LED.
cam.stopPreview();
cam.release();

 

 
 
 

Check if a service is running on Android

Step 1)
make a function isMyServiceRunning
private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}
 
Step 2)
call the function with name of service class
isMyServiceRunning(MyService.class)

 

Thursday 19 March 2015

Android Detecting Internet Connection Status

Detect internet connection

First)
Add permission to manifest.xml

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

<!-- Network State Permissions -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 
Second)
Make a class ConnectDetect

public class ConnectDetect {
	
private Context context;
	
public ConnectDetect(Context context){
	this.context = context;
     }

public boolean isConnectingToInternet(){
	ConnectivityManager connectivity = (ConnectivityManager) context
                       .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) 
		{
	NetworkInfo[] info = connectivity.getAllNetworkInfo();
		if (info != null) 
	         for (int i = 0; i < info.length; i++) 
		if (info[i].getState() == NetworkInfo.State.CONNECTED)
			{
			return true;
			}
		  }
		  return false;
	}
}
 
Third)
Make a object of ConnectDetect and call funtion  isConnectingToInternet to check
internet status  
ConnectDetect cd = new ConnectDetect(getApplicationContext());
Boolean isInternetPresent = cd.isConnectingToInternet();
//Returns true if connected to internet ,false if not connected to internet

Programatically take a screenshot of view on Android

Copy, paste and modify the function according to need 
,this function create a Bitmap of current screen view 
 and save the .png file to sd card .

so add this permission in manifest to   
<uses-permission android:name="android.permission
               .WRITE_EXTERNAL_STORAGE"/> 
 
private void captureScreen() {
        View v = getWindow().getDecorView().getRootView();
        v.setDrawingCacheEnabled(true);
        Bitmap bmp = Bitmap.createBitmap(v.getDrawingCache());
        v.setDrawingCacheEnabled(false);
        try {
            FileOutputStream fos = new FileOutputStream(
                   new File(Environment.getExternalStorageDirectory()
                  .toString(), "SCREEN" + System.currentTimeMillis() 
                                                 + ".png"));
            bmp.compress(CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Get Android Phone screen dimensions in pixels

You can get the Android Phone Screen dimensions  in the following ways :

1)
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
 
2)
Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();  // deprecated
int height = display.getHeight();  // deprecated

3)
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels; 
 

 
 

Close/hide the Android Soft Keyboard

 //Show soft-keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams 
                       .SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//hide keyboard :
 getWindow().setSoftInputMode(WindowManager.LayoutParams 
                         .SOFT_INPUT_STATE_ALWAYS_HIDDEN);

SharedPreferences in Android to store, fetch and edit values .

You can store,fetch and edit data for specific app in Shared Preferences in following way  :-

Way 1)

Initialize sharedPrefrences object: 
//declare it in onCreate() 
SharedPreferences preferences = this.getSharedPreferences(
      "com.example.android", Context.MODE_PRIVATE);
 
To edit and save preferences(same it used to store new values):
SharedPreferences.Editor editor =preferences.edit();   
editor.putString("Key","Value"); 
editor.commit();
 
To read preferences:
String name = preferences.getString("Key","");

 
 
Way 2)

Initialize sharedPrefrences object:  
 //declare it in onCreate()
SharedPreferences preferences = PreferenceManager. 
                                 getDefaultSharedPreferences(this);
 
To edit and save preferences(same it used to store new values):
 SharedPreferences.Editor editor = preferences.edit();
 editor.putString("key","value");
 editor.commit();
 
To read preferences:
String name = preferences.getString("Key","");