Showing posts with label Broadcast receiver. Show all posts
Showing posts with label Broadcast receiver. Show all posts

Tuesday, September 24, 2013

Check internet connection using broadcast receiver

In android device basically 2 types of internet connectivity.

1. Mobile internet (GPRS)
2. Wifi internet connectivity

If we need to perform some operation on internet connectivity change,Here is the full code for it.It is very useful to sync application data in offline and online mode also.


Let's Start 


  • First of all give below permission just above <application> tag.

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


  • We are using broadcast receiver for notification. Broadcast receiver provides the functionality of background process.
  • It is running in back end continuously and will give notification.For this purpose we need to register our broadcast receiver in AndroidMenifest.xml file.  
  • Write down below code before completion of </application> tag(In <Application> tag).
<receiver
            android:name="<package_name>.NetworkChangeReceiver"
            android:label="NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>


  • Full AndroidMenifest.xml is given below:

AndroidMenifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.broadcast_internetcheck"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.broadcast_internetcheck.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name="com.example.broadcast_internetcheck.NetworkChangeReceiver"
            android:label="NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>
    </application>

</manifest>


  • Now Create on global file for check internet connectivity.It will return the result of which internet connectivity is currently active.
  • Create new java class file and named it, NetworkUtil.java

NetworkUtil.java


public class NetworkUtil {

public static int TYPE_WIFI = 1;
   public static int TYPE_MOBILE = 2;
   public static int TYPE_NOT_CONNECTED = 0;
    
    
   public static int getConnectivityStatus(Context context) {
       ConnectivityManager cm = (ConnectivityManager) context
               .getSystemService(Context.CONNECTIVITY_SERVICE);
 
       NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
       if (null != activeNetwork) {
           if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
               return TYPE_WIFI;
            
           if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
               return TYPE_MOBILE;
       } 
       return TYPE_NOT_CONNECTED;
   }
    
   public static String getConnectivityStatusString(Context context) {
       int conn = NetworkUtil.getConnectivityStatus(context);
       String status = null;
       if (conn == NetworkUtil.TYPE_WIFI) {
           status = "Wifi enabled";
       } else if (conn == NetworkUtil.TYPE_MOBILE) {
           status = "Mobile data enabled";
       } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
           status = "Not connected to Internet";
       }
       return status;
   }
}


  • If you get some error,than press Ctrl + Shift + O. It will import missing inbuilt library.
  • Create new java class file and named it, NetworkChangeReceiver.java and write down below code. It extends BroadcastReceiver. We have already registered it on AndroidMenifest.xml file.

NetworkChangeReceiver.java



import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class NetworkChangeReceiver extends BroadcastReceiver{

@Override
   public void onReceive(final Context context, final Intent intent) {
 
       String status = NetworkUtil.getConnectivityStatusString(context);
 
       Toast.makeText(context, status, Toast.LENGTH_LONG).show();
   }
}

  • Now run this project and get output. Remember that for Wifi result run it on real device. It may not give the gesult of WIFI Connectivity.

Saturday, August 10, 2013

Broadcast Receiver manual On/Off

Ya Its true, you can also enable / disable Broadcast Receiver in android development.

You have to register it for enable Receiver and unregistered for disable it.One more thing whatever you want to execute in Receiver, You need to create on separate java file and also extends BroadcastReceiver.

Here is full source code and step to set Broadcast Receiver manually.


  • Create new android project. Name it: BroadcastReceiverManual
  • add below code into activity_main.xml file. 

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" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:orientation="vertical" >

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="registerBroadcastReceiver"
            android:padding="15dp"
            android:text="Register"
            tools:context=".RegisterUnregister" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="unregisterBroadcastReceiver"
            android:padding="15dp"
            android:text="Unregister"
            tools:context=".RegisterUnregister" />
    </LinearLayout>

</RelativeLayout><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" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:orientation="vertical" >

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="registerBroadcastReceiver"
            android:padding="15dp"
            android:text="Register"
            tools:context=".RegisterUnregister" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="unregisterBroadcastReceiver"
            android:padding="15dp"
            android:text="Unregister"
            tools:context=".RegisterUnregister" />
    </LinearLayout>

</RelativeLayout>


  • Add below code in activity_main.java file.

activity_main.java


public class MainActivity extends Activity {

UserDefinedBroadcastReceiver broadCastReceiver = new UserDefinedBroadcastReceiver();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
    // This method enables the Broadcast receiver for
    // "android.intent.action.TIME_TICK" intent. This intent get
    // broadcasted every minute.

  public void registerBroadcastReceiver(View view) {
 
     this.registerReceiver(broadCastReceiver, new IntentFilter(
           "android.intent.action.TIME_TICK"));
     Toast.makeText(this, "Registered broadcast receiver", Toast.LENGTH_SHORT)
           .show();
  }
 
  /*
   * This method disables the Broadcast receiver
    */
  public void unregisterBroadcastReceiver(View view) {
 
     this.unregisterReceiver(broadCastReceiver);
 
     Toast.makeText(this, "unregistered broadcst receiver", Toast.LENGTH_SHORT)
           .show();
  }
}


  • Create on more file which extends BroadcastReceiver, Name it: UserDefinedBroadcastReceiver.java in project package.
  • Add below code in UserDefinedBroadcastReceiver.java file.


UserDefinedBroadcastReceiver.java



public class UserDefinedBroadcastReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
//You can do the processing here update the widget/remote views.
        StringBuilder msgStr = new StringBuilder("Current time : ");
        Format formatter = new SimpleDateFormat("hh:mm:ss a");
        msgStr.append(formatter.format(new Date()));
        Toast.makeText(context, msgStr, Toast.LENGTH_SHORT).show();
}

}


That it. Now run the project and check output.



Download Full Source Code: Download