Check whether the device is in roaming or not after 2 seconds in android

1.4k views Asked by At

I am developing an app in android where i need to check that whether the device is in roaming or not. when i use this code,

Handler m = new Handler();

        m.postDelayed(new Runnable()
        { 
            public void run() 
            { 
                        if(telephonyManager.isNetworkRoaming())
                        {
                            Toast.makeText(getApplicationContext(), "Network is in Roaming", Toast.LENGTH_LONG).show();
                        }
                        else
                        {
                            Toast.makeText(getApplicationContext(), "Network not in Roaming", Toast.LENGTH_LONG).show();
                        }
            } 
        }, 2000);

But it keeps on printing the toast after every 2 seconds. I want the toast to be printed only when the cell location is changed from normal network to roaming.

1

There are 1 answers

2
Yogesh Somani On

Declare a BroadcastReceiver:

  public class ConnectivityChangedReceiver extends BroadcastReceiver{

  @Override
  public void onReceive( Context context, Intent intent )
  {
     //call the method of showing toast on network roaming changed. Make sure that method is in another activity. 
  }
  }

Declare this receiver in manifest :

    <receiver android:name="com.yourproject.service.ConnectivityChangedReceiver"
        android:label="NetworkConnection">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
        </intent-filter> 
    </receiver>