Showing posts with label check current state. Show all posts

Tuesday, 9 June 2015

Turn ON and OFF Bluetooth and check current state of Bluetooth

In this android example we write code for turn ON or OFF Bluetooth and check current state of Bluetooth is currently ON or OFF.

CREATE NEW ANDROID PROJECT

Step 1: Write code into 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ImageButton
        android:id="@+id/turnON"
        android:layout_width="130dp"
        android:layout_height="130dp"
        android:layout_alignLeft="@+id/textView2"
        android:layout_alignParentTop="true"
        android:layout_marginTop="64dp"
        android:src="@drawable/bluetoothoff" />

    <TextView
        android:id="@+id/Bluetooth"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="18dp"
        android:layout_weight="1"
        android:text="bluetooth ON OFF"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/discoverable"
        android:layout_below="@+id/turnON"
        android:layout_marginTop="24dp"
        android:text="make discover"
        android:textSize="18sp" />

    <ImageButton
        android:id="@+id/discoverable"
        android:layout_width="130dp"
        android:layout_height="130dp"
        android:layout_alignLeft="@+id/Bluetooth"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="15dp"
        android:src="@drawable/bluetoothdiscoveroff" />


</RelativeLayout>


Step 2: Write code into MainActivity.java

package dev.androidapplink.bluetoothapp;

import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

public class MainActivity extends Activity {

// define bluetooth control
ImageButton turnONOFF;
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

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

// load bluetooth control
turnONOFF = (ImageButton) findViewById(R.id.turnON);
final ImageButton discoverable = (ImageButton) findViewById(R.id.discoverable);

cheackBluetoothStastus();

// Implement click event and set image according to status and make
// bluetooth on off
// working like toggle button
turnONOFF.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

if (!bluetooth.isEnabled()) {

turnONOFF.setImageResource(R.drawable.bluetoothon);

startActivityForResult(new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE), 0);

} else {
bluetooth.disable();
turnONOFF.setImageResource(R.drawable.bluetoothoff);
discoverable
.setImageResource(R.drawable.bluetoothdiscoveroff);
}

}
});
discoverable.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Implement click event and set image according to status
if (!bluetooth.isDiscovering()) {

discoverable
.setImageResource(R.drawable.bluetoothdiscoveroff);
turnONOFF.setImageResource(R.drawable.bluetoothon);
startActivityForResult(new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE), 0);
discoverable
.setImageResource(R.drawable.bluetoothdiscoveron);

}
}
});

}

// Check bluetooth status and set image according to
private void cheackBluetoothStastus() {
// TODO Auto-generated method stub

if (bluetooth.isEnabled()) {
turnONOFF.setImageResource(R.drawable.bluetoothon);

} else {
turnONOFF.setImageResource(R.drawable.bluetoothoff);

}
}

}

NOTE: Give below permission in Androidmanifest.xml
Its allow to access Bluetooth settings.

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

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

Step 3: Run Your Project:

Turn on Bluetooth



Bluetooth is on:

Make Discover:

Discovering for 120 seconds:



Friday, 5 June 2015

Android battery level indicator

In this android example we write a simple code to get battery level in percentage.before to write code you need to know the basics of  broadcaster receiver first. let me explain the stuffs about it.


- Intent.Action_Battery_Changed : This is a sticky broadcast containing the charging state, level, and other information about the battery.The android BatteryManager class contains strings and constants used for values in the ACTION_BATTERY_CHANGED Intent. Among the various constants available.

- registerReceiver(BroadcastReceiver receiver, IntentFilter filter) : We need to register for Action_Battery_Changed broadcast in this method. This will get invoked whenever this event occurs. Since this is a sticky Intent, it keeps on broadcasting once registered.

- String EXTRA_HEALTH: integer containing the current health constant.

- String EXTRA_ICON_SMALL: integer containing the resource ID of a small status bar icon indicating the current battery state.

- EXTRA_LEVEL: integer field containing the current battery level, from 0 to EXTRA_SCALE.

- EXTRA_PLUGGED: integer indicating whether the device is plugged in to a power source; 0 means it is on battery, other constants are different types of power sources.

- EXTRA_PRESENT: Boolean indicating whether a battery is present.

- EXTRA_SCALE: integer containing the maximum battery level.

- EXTRA_STATUS: integer containing the current status constant.

- EXTRA_TECHNOLOGY: String describing the technology of the current battery.

- EXTRA_TEMPERATURE: integer containing the current battery temperature.

- EXTRA_VOLTAGE: integer containing the current battery voltage level.

BATTERY_PLUGGED_AC: Power source is an AC charger.

- BATTERY_PLUGGED_USB: Power source is an  USB charger.

To know More About CLICK HERE:

I hope all above stuff is helpful for you.Now let's go for the code.

Step 1: Write code into activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textfield"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="40dip" />

    <ProgressBar
        android:id="@+id/progressbar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dip"
        android:max="100"
        android:maxHeight="500dip"
        android:maxWidth="300dip"
        android:minHeight="100dip"
        android:minWidth="200dip" />

</LinearLayout>

Step 2: Write code into MainActivity.java

package dev.androidapplink.batterylevelapp;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {

private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
int level = i.getIntExtra("level", 0);
ProgressBar pb = (ProgressBar) findViewById(R.id.progressbar);
pb.setProgress(level);
TextView tv = (TextView) findViewById(R.id.textfield);
tv.setText("Battery Level: " + Integer.toString(level) + "%");
}

};

// Called when the activity is first created. 
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(mBatInfoReceiver, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));
}
}

NOTE:No need any permission in AndroidManifest.xml 

Step 3: Run your project:


Wednesday, 3 June 2015

Check Network state and type | Wifi | Mobile 2G/3G |

In this android example i show you some interesting code about network state. just write a simple android code to get network information.
  1. Check network connection type WiFi/Mobile data etc.
  2. Check state connected or disconnected
  3. Previously activated network
Before starting example we should know some thing about KEY and Meaning of connectivity manager API.The intent never contains any data or type information, but some possible keys are provided in the ConnectivityManager API:


KEY and MEANING:

EXTRA_EXTRA_INFO : Contains additional information about the network state.

EXTRA_IS_FAILOVER : A Boolean that indicates whether this network is used as a failover for another, previously active network.

EXTRA_NETWORK_INFO : The Network Info object containing all information about the current state of this network type.

EXTRA_NO_CONNECTIVITY :  A Boolean that is set to true if the device has no connectivity at all.
EXTRA_OTHER_NETWORK_INFO : The Network Info object containing all information about the current state of a possible alternative network type.

EXTRA_REASON : The reason of the connectivity change.

CREATE NEW ANDROID PROJECT

Step 1: Write code into activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/tvinfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:text="@string/hello_world"
        android:textSize="20sp" />

</LinearLayout>


Step 2: Write code into MainActivity.java

package dev.androidapplink.connectionstatusapp;

import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.TextView;


public class MainActivity extends Activity {
private ConnectivityReceiver receiver = null;
private TextView txtNetworkInfo = null;

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

txtNetworkInfo = (TextView) findViewById(R.id.tvinfo);
receiver = new ConnectivityReceiver();

registerReceiver(receiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}

@Override
protected void onDestroy() {
unregisterReceiver(receiver);

super.onDestroy();
}

private String getNetworkStateString(NetworkInfo.State state) {
String stateString = "Unknown";

switch (state) {
case CONNECTED:
stateString = "Connected";
break;
case CONNECTING:
stateString = "Connecting";
break;
case DISCONNECTED:
stateString = "Disconnected";
break;
case DISCONNECTING:
stateString = "Disconnecting";
break;
case SUSPENDED:
stateString = "Suspended";
break;
default:
stateString = "Unknown";
break;
}

return stateString;
}

private class ConnectivityReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
// In this example i using " EXTRA_NETWORK_INFO " The NetworkInfo object containing all information about the current state of this network type

NetworkInfo info = intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

if (null != info) {
String state = getNetworkStateString(info.getState());
String stateString = info.toString().replace(',', '\n');

String infoString = String.format(
"Network Type: %s\nNetwork State: %s\n\n%s",
info.getTypeName(), state, stateString);

Log.i("ConnTest", info.getTypeName());
Log.i("ConnTest", state);
Log.i("ConnTest", info.toString());

txtNetworkInfo.setText(infoString);
}
}
}
}

NOTE:Give permission in AndroidManifest.xml

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


Step 3: Run your project:


WiFi Connected Or Disconnected:




 Bobile data 2G and 3G connection:







Sunday, 31 May 2015

SDcard information or check current status

          Hello friends, in this android example i show you how to get storage information of SDcard, And check status of SDcard like its mounted or available in devise or not.here is simple code is to get Total size of SDcard and Remaining space.Lets go for coding.In this we get size of storage in GB,MB,KB and Byte.


CREATE NEW ANDROID PROJECT


Step 1: Write code into activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/state"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="15dip"
        android:textStyle="bold"
        android:typeface="normal" >
    </TextView>

    <TextView
        android:id="@+id/info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dip" >
    </TextView>

</LinearLayout>


Step 2:Write code into MainActivity.java


package dev.Androidapplink.sdcardinfoapp;

import java.text.NumberFormat;

import dev.Androidapplink.sdcardinfoapp.R;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.widget.TextView;

public class MainActivity extends Activity 
{
//the statistics of the SD card
private StatFs stats;
//the state of the external storage
private String externalStorageState;

//the total size of the SD card
private double totalSize;
//the available free space
private double freeSpace;

//a String to store the SD card information
private String outputInfo;
//a TextView to output the SD card state
private TextView tv_state;
//a TextView to output the SD card information
private TextView tv_info;

//set the number format output
private NumberFormat numberFormat;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //initialize the Text Views with the data at the main.xml file
        tv_state = (TextView)findViewById(R.id.state);
        tv_info = (TextView)findViewById(R.id.info);
        
        //get external storage (SD card) state
        externalStorageState = Environment.getExternalStorageState();
        
        //checks if the SD card is available in device 
        if(externalStorageState.equals(Environment.MEDIA_MOUNTED)
        || externalStorageState.equals(Environment.MEDIA_UNMOUNTED)
        || externalStorageState.equals(Environment.MEDIA_MOUNTED_READ_ONLY))
        {
        //obtain the stats from the root of the SD card.
        stats = new StatFs(Environment.getExternalStorageDirectory().getPath());
       
        //Add 'Total Size' to the output string:
        outputInfo = "\nTotal Size:\n";
       
        //total usable size
        totalSize = stats.getBlockCount() * stats.getBlockSize();
       
        //initialize the NumberFormat object
        numberFormat = NumberFormat.getInstance();
        //disable grouping
        numberFormat.setGroupingUsed(false);
        //display numbers with two decimal places
        numberFormat.setMaximumFractionDigits(2); 
       
        //SD card's total size in gigabytes, megabytes, kilobytes and bytes
        outputInfo += "Size in gigabytes: " + numberFormat.format((totalSize / (double)1073741824)) + " GB \n"
        + "Size in megabytes: " + numberFormat.format((totalSize / (double)1048576)) + " MB \n" 
        + "Size in kilobytes: " + numberFormat.format((totalSize / (double)1024)) + " KB \n" 
        + "Size in bytes: " +  numberFormat.format(totalSize) + " B \n"; 
       
        //Add 'Remaining Space' to the output string:
        outputInfo += "\nRemaining Space:\n";
       
        //available free space
        freeSpace = stats.getAvailableBlocks() * stats.getBlockSize();
       
        //SD card's available free space in gigabytes, megabytes, kilobytes and bytes
        outputInfo += "Size in gigabytes: " + numberFormat.format((freeSpace / (double)1073741824)) + " GB \n"
        + "Size in megabytes: " + numberFormat.format((freeSpace / (double)1048576)) + " MB \n" 
        + "Size in kilobytes: " + numberFormat.format((freeSpace / (double)1024)) + " KB \n"
        + "Size in bytes: " + numberFormat.format(freeSpace) + " B \n"; 
       
        //output the SD card state
        tv_state.setTextColor(Color.GREEN);
        tv_state.setText("SD card found! SD card is " + externalStorageState +".");
       
        //output the SD card info
        tv_info.setText(outputInfo);
        }
        else //external storage was not found
        {
        //output the SD card state
        tv_state.setTextColor(Color.RED);
        tv_state.setText("SD card not found! SD card state is \"" + externalStorageState + "\".");
        }
    }
}

NOTE:Give permission in AndroidManifest.xml

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


Step 3:Run project to see Output:





Adjust screen brightness in android

In this tutorial i show you,how to adjust screen brightness programatically in android.In this example we learn get current screen brightness state and changing screen brightness.

CREATE NEW ANDROID PROJECT

Step 1: Write code into activity_main.xml

<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:text="Slide seekbar to change the brightness" />

    <TextView
        android:id="@+id/txtPercentage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:text="0%"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <SeekBar
        android:id="@+id/brightbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp" />


</LinearLayout>

Step 2: Write code into MainActivity.java

package dev.Androidapplink.setscreenbrightnessapp;

import dev.Androidapplink.setscreenbrightnessapp.R;

import android.app.Activity;
import android.content.ContentResolver;
import android.os.Bundle;
import android.provider.Settings.System;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class MainActivity extends Activity {


//Seek bar object
private SeekBar brightbar;

//Variable to store brightness value
private int brightness;

//handle to the system's settings
private ContentResolver cResolver;

//Window object store a reference to the current window
private Window window;

TextView txtPerc;
   

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

        //Instantiate seekbar object
brightbar = (SeekBar) findViewById(R.id.brightbar);

txtPerc = (TextView) findViewById(R.id.txtPercentage);

        //Get the content resolver
cResolver = getContentResolver();

        //Get the current window
window = getWindow();

        //Set the seekbar range between 0 and 255
brightbar.setMax(255);

        //Set the seek bar progress to 1
brightbar.setKeyProgressIncrement(1);

try {
        //Get the current system brightness state
brightness = System.getInt(cResolver, System.SCREEN_BRIGHTNESS);
float perc = (brightness /(float)255)*100;
txtPerc.setText((int)perc + "%");
} catch (Exception e) {
// TODO: handle exception
        //Throw an error case it couldn't be retrieved
Log.e("Error", "cannot access system brightness.");
e.printStackTrace();
}

//Set the progress of the seek bar based on the system's brightness
brightbar.setProgress(brightness);


//Register OnSeekBarChangeListener, so it can actually change values
brightbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub

//Set the system brightness using the brightness variable value
System.putInt(cResolver, System.SCREEN_BRIGHTNESS, brightness);
//Get the current window attributes
LayoutParams layoutpars = window.getAttributes();

//Set the brightness of this window
layoutpars.screenBrightness = brightness / (float)255;
//Apply attribute changes to this window
window.setAttributes(layoutpars);

}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub

//Nothing handled here
}

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
//Set the minimal brightness level
if(progress<=20)
{

brightness=20;
}
else //brightness is greater than 20
{
//Set brightness variable based on the progress bar 
brightness = progress;
}

//Calculate the brightness percentage
float perc = (brightness /(float)255)*100;

//Set the brightness percentage 
txtPerc.setText((int)perc + "%");

}
});
}
//IT WORK ONLY,IF SCREEN BRIGHTNESS IS NOT SETED IN "AUTO BRIGHTNESS MODE".

}

NOTE: Give permission in AndroidManifest.xml
It allow to change setting.

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

Step 3: Run project and see Output:





Follow me Share