Last active
July 11, 2019 03:08
-
-
Save esantiago1/6daadea3b3ea9259900bee66f3abe5ea to your computer and use it in GitHub Desktop.
Detect network change
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<manifest xmlns:android="http://schemas.android.com/apk/res/android" | |
package="com.demo.myapplication"> | |
<uses-permission android:name="android.permission.INTERNET" /> | |
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> | |
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> | |
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> | |
<application | |
android:allowBackup="true" | |
android:icon="@mipmap/ic_launcher" | |
android:label="@string/app_name" | |
android:roundIcon="@mipmap/ic_launcher_round" | |
android:supportsRtl="true" | |
android:theme="@style/AppTheme"> | |
<activity android:name=".MainActivity"> | |
<intent-filter> | |
<action android:name="android.intent.action.MAIN" /> | |
<category android:name="android.intent.category.LAUNCHER" /> | |
</intent-filter> | |
</activity> | |
</application> | |
</manifest> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainActivity extends AppCompatActivity { | |
private final IntentFilter filterNetwork = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
registerReceiver(networkReceiver, filterNetwork); | |
} | |
private final BroadcastReceiver networkReceiver = new BroadcastReceiver() { | |
@Override | |
public void onReceive(Context context, Intent intent) { | |
if (isOnline()) { | |
Toast.makeText(MainActivity.this,"Internet",Toast.LENGTH_SHORT).show(); | |
} else { | |
Toast.makeText(MainActivity.this,"No internet",Toast.LENGTH_SHORT).show(); | |
} | |
} | |
}; | |
public boolean isOnline() { | |
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); | |
assert connMgr != null; | |
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); | |
return (networkInfo != null && networkInfo.isConnected()); | |
} | |
@Override | |
protected void onDestroy() { | |
super.onDestroy(); | |
unregisterReceiver(networkReceiver); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment