Sunday, 12 April 2015

Save Activity State in Android

Save activity state in android apps (for example when we rotate our device portrait to landscape or landscape to portrait the values which we had filled in EditText gone away)

You need to override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter like this

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  // Save UI state changes to the savedInstanceState.
  // This bundle will be passed to onCreate if the process is
  // killed and restarted.
  savedInstanceState.putBoolean("BooleanValueKey", true);
  savedInstanceState.putDouble("DoubleValueKey", 1.9);
  savedInstanceState.putInt("IntValueKey", 1);
  savedInstanceState.putString("StringValueKey", "Welcome to Android Code Portal");
  // etc.
}
 
The Bundle is essentially a way of storing a NVP ("Name-Value Pair") map, and it will 
get passed in to onCreate() and also onRestoreInstanceState() where you'd extract 
the values like this: 

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.
  boolean booleanValue = savedInstanceState.getBoolean("BooleanValueKey");
  double doubleValue = savedInstanceState.getDouble("DoubleValueKey");
  int intValue = savedInstanceState.getInt("IntValueKey");
  String stringValue = savedInstanceState.getString("StringValueKey");
}
 

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;