I want to verify the Android system networks continuously in this way, but i think that in this form is not correct, my service should update if the connection on wifi or other network is available.
public class ObjService extends Service{
private final static int NOTIFICATION=1;
public static boolean process;
private NotificationManager state;
private NotificationCompat.Builder objBuilder;
public void onCreate(){
process=true;
state=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
objBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Title")
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.launchimg))
.setSmallIcon(R.drawable.notification_img);
Thread checker=new Thread(){//1
public void run(){//2
while (process){//3
if (verifyConnection()){//4
updateNotificationService("Service is available");
}else{
updateNotificationService("Service is not available");
}//4
try{
Thread.sleep(6000);
}catch(InterruptedException e){
//..printLog..
}
}//3
};//2
};//1
checker.start();
.
.
.
my function verifyConnection() is:
public boolean verifyConnection() {
boolean flag = true;
ConnectivityManager connec = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] net = connec.getAllNetworkInfo();
if (!net[0].isAvailable() && !net[1].isAvailable())
{
flag = false;
}
return flag;
}
updateNotificationService() is:
public void updateNotificacionService(String arg){
objBuilder.setContentText(arg)
.setWhen(System.currentTimeMillis());
state.notify(NOTIFICATION, objBuilder.build());
}
Try this code below to listen whether the connection exist, if the connection state changes it notifies the change,
public class NetworkStateReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
Log.d("app","Network connectivity change");
if(intent.getExtras()!=null) {
NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
Log.i("app","Network "+ni.getTypeName()+" connected");
}
}
if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
Log.d("app","There's no network connectivity");
}
}
}
Then for manifest,
<receiver android:name=".NetworkStateReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Reference: Internet listener Android example
Android 7.0 (API level 24) placed limitations on broadcasts, as
described in Background Optimization. Android 8.0 (API level 26) makes
these limitations more stringent.
Apps can use Context.registerReceiver() at runtime to register a
receiver for any broadcast, whether implicit or explicit.
Documentation reference.
So, here is a utility class that utilizes a context registered BroadcastReceiver , and LifeCycleObserver for achieving Single-responsibility principle
class ConnectionUtil implements LifecycleObserver {
private ConnectivityManager mConnectivityMgr;
private Context mContext;
private NetworkStateReceiver mNetworkStateReceiver;
interface ConnectionStateListener {
void onAvailable(boolean isAvailable);
}
ConnectionUtil(Context context) {
mContext = context;
mConnectivityMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
((AppCompatActivity) mContext).getLifecycle().addObserver(this);
}
void onInternetStateListener(ConnectionStateListener listener) {
mNetworkStateReceiver = new NetworkStateReceiver(listener);
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
// Registering the Context Registered Receiver
mContext.registerReceiver(mNetworkStateReceiver, intentFilter);
}
#OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
// Removing lifecycler owner observer
((AppCompatActivity) mContext).getLifecycle().removeObserver(this);
// Unregistering the Context Registered Receiver
if (mNetworkStateReceiver != null)
mContext.unregisterReceiver(mNetworkStateReceiver);
}
public class NetworkStateReceiver extends BroadcastReceiver {
ConnectionStateListener mListener;
public NetworkStateReceiver(ConnectionStateListener listener) {
mListener = listener;
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getExtras() != null) {
NetworkInfo activeNetworkInfo = mConnectivityMgr.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.getState() == NetworkInfo.State.CONNECTED) {
// Connected to the internet
mListener.onAvailable(true);
} else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
// Not connected to the internet
mListener.onAvailable(false);
}
}
}
}
}
Manifest permission
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Usage:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectionUtil mConnectionMonitor = new ConnectionUtil(this);
mConnectionMonitor.onInternetStateListener(new ConnectionUtil.ConnectionStateListener() {
#Override
public void onAvailable(boolean isAvailable) {
if(isAvailable)
Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Disconnected", Toast.LENGTH_SHORT).show();
}
});
}
}
Note: NetworkInfo is deprecated as of API 29, and you can use ConnectivityManager.NetworkCallback with its onAvailable() & onLost() callbacks for the same purpose instead of using a BroadcastReceiver. This answer can guide to target this purpose.
Related
I want to check whether Internet connection is turned on or not when app starts. It should allow to start if internet is connected. Else display a error message and direct user to settings. Message need to be displayed until Internet connection is turned on.
Already I finished connection check function and alert display function. How could I listen whether internet is turned on or not after user directed to settings
connection check function is,
public boolean connectionIsAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetwork != null && wifiNetwork.isConnected()) {
return true;
}
NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mobileNetwork != null && mobileNetwork.isConnected()) {
return true;
}
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
return true;
}
return false;
}
and alert display,
public void displayAlertDialog(final Context context){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context, AlertDialog.THEME_TRADITIONAL);
alertDialogBuilder.setMessage("Would you like to enable it?")
.setTitle("No Internet Connection")
.setPositiveButton(" Enable Internet ", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent dialogIntent = new Intent(android.provider.Settings.ACTION_SETTINGS);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(dialogIntent);
}
});
alertDialogBuilder.setNegativeButton(" Cancel ", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
In my onCreate I check like,
if(connectionIsAvailable(getApplicationContext())) {
welcomeThread.start();
} else {
displayAlertDialog(LoadingScreenActivity.this);
}
Help me how could I listen whether internet is turned on or not after user directed to settings. Thanks in advance.
Register receiver in manifest file
<!-- Broadcast receiver declaration in manifest file and make sure to enable it -->
<receiver
android:name=".InternetConnectorReceiver"
android:enabled="true">
<intent-filter>
<!-- Intent filters for broadcast receiver -->
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
Required permissions
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
InternetConnectorReceiver.class
public class InternetConnectorReceiver extends BroadcastReceiver {
// you can perform the action based on InternetConnected or not based on value of this variable.
public static boolean IsInternetConnected = true;
public InternetConnectorBroadcastReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
try {
boolean isVisible = NameOfapplicationclass.isActivityVisible();
// If it is visible then trigger the task else do nothing
if (isVisible == true) {
if (isInternetConnected(context)) {
IsInternetConnected = true;
}
else
{
IsInternetConnected = false;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static boolean isInternetConnected(Context context) {
ConnectivityManager cmObj = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cmObj.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
return true;
}
return false;
}
Add Following code in application class
public static boolean activityVisible;
public static boolean isActivityVisible() {
return activityVisible; // return true or false
}
public static void activityResumed() {
activityVisible = true;// this will set true when activity resumed
}
public static void activityPaused() {
activityVisible = false;// this will set false when activity paused
}
You have to use BroadcasrReceive
try this.
Create class for BroadcastReceiver
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
//Do your code
}
}
and register it in manifest file like this
<receiver android:name=".NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--Custom Broadcast Receiver for checking Internet Connectivity-->
<receiver
android:name=".extras.ConnectivityReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<!--End-->
Connectivity Receiver Class:
public class ConnectivityReceiver extends BroadcastReceiver {
public static ConnectivityReceiverListener connectivityReceiverListener;
public ConnectivityReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent arg1) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();
if (connectivityReceiverListener != null) {
connectivityReceiverListener.onNetworkConnectionChanged(isConnected);
}
}
/**
* Checking if internet connection is active or not
* #return
*/
public static boolean isConnected() {
ConnectivityManager
cm = (ConnectivityManager) MyApplication.getInstance().getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();
}
public interface ConnectivityReceiverListener {
void onNetworkConnectionChanged(boolean isConnected);
}
}
Activity Code:
public class HomeActivity extends AppCompatActivity
implements ConnectivityReceiver.ConnectivityReceiverListener {
/**
* Callback will be triggered when there is change in
* network connection
*/
#Override
public void onNetworkConnectionChanged(boolean isConnected) {
if (!isConnected) {
// show dialog \\
} else {
// check if dialog is visible \\
// if visible then dismiss else do your stuff \\
}
}
#Override
protected void onResume() {
super.onResume();
// Register connection status listener \\
MyApplication.getInstance().setConnectivityListener(this);
}
}
My Application class code and set it in manifest:
public class MyApplication extends Application {
private static MyApplication mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
//-------Broadcast Receiver for Checking Internet Connection----------\\
public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) {
ConnectivityReceiver.connectivityReceiverListener = listener;
}
//----------------------------------------------------------------------\\
}
When phone's network status changed, it will send a broadcast. So you just need a BroadcastReceiver.
For more detail check official documentation
I want to check internet connection continuously on every activity with the broadcastreceiver. I already write the code and it perfectly working. But I want to use it in every activity. How can I modify this code?
public class MainActivity extends Activity {
private static final String LOG_TAG = "CheckNetworkStatus";
private NetworkChangeReceiver receiver;
private boolean isConnected = false;
private TextView networkStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new NetworkChangeReceiver();
registerReceiver(receiver, filter);
networkStatus = (TextView) findViewById(R.id.networkStatus);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onDestroy() {
Log.v(LOG_TAG, "onDestory");
super.onDestroy();
unregisterReceiver(receiver);
}
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
Log.v(LOG_TAG, "Receieved notification about network status");
isNetworkAvailable(context);
}
private boolean isNetworkAvailable(Context context) {
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) {
if(!isConnected){
Log.v(LOG_TAG, "Now you are connected to Internet!");
networkStatus.setText("Now you are connected to Internet!");
isConnected = true;
//do your processing here ---
//if you need to post any data to the server or get status
//update from the server
}
return true;
}
}
}
}
Log.v(LOG_TAG, "You are not connected to Internet!");
networkStatus.setText("You are not connected to Internet!");
isConnected = false;
return false;
}
}
}
I want to use it in every activity. How can I modify this code?
Create a BaseActivity class which extends AppCompatActivity, and then make all of your Activity classes extend this BaseActivity class. Put your code to check internet connection in the BaseActivity class. cheers :)
Create a BaseActivity without a layout which extends to AppCompatActivity or Activity.
Extend all the other activities (or the one where you need to check for internet connectivity) of your app to the BaseActivity.
Now use a broadcast receiver in the BaseActivity which constantly checks for network and connectivity state.
Reference code for BaseActivity. (In my case, I show a snackbar when there is no connection detected.)
public class BaseActivity extends AppCompatActivity {
private static final int WIFI_ENABLE_REQUEST = 0x1006;
private BroadcastReceiver mNetworkDetectReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
checkInternetConnection();
}
};
private AlertDialog mInternetDialog;
private boolean isConnected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isConnected = false;
registerReceiver(mNetworkDetectReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
protected void onDestroy() {
unregisterReceiver(mNetworkDetectReceiver);
super.onDestroy();
}
private void checkInternetConnection() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = manager.getActiveNetworkInfo();
if (ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
isConnected =true;
showNoConnectionSnackBar("Connected", isConnected, 1500);
} else {
isConnected= false;
showNoConnectionSnackBar("No active Internet connection found.", isConnected,6000);
}
}
private void showNoConnectionSnackBar(String message, boolean isConnected, int duration) {
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content),
message, duration);
View sbView = snackbar.getView();
TextView textView = (TextView) sbView
.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(ContextCompat.getColor(this, android.R.color.white));
if (isConnected){
sbView.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
}else{
sbView.setBackgroundColor(getResources().getColor(R.color.google_button_color));
snackbar.setAction("Turn On", new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent internetOptionsIntent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
startActivityForResult(internetOptionsIntent, WIFI_ENABLE_REQUEST);
}
});
snackbar.setActionTextColor(getResources().getColor(R.color.colorPrimary));
}
snackbar.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == WIFI_ENABLE_REQUEST) {
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
Create a service. start the service in the launcher activity and put the network check code in that service.
public class NetworkServiceextends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//register receiver here
// connection check code
return START_STICKY;
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onDestroy() {
super.onDestroy();
// unregister receiver
}
}
You can put your BroadcastReceiver in it's own class, and then declare/register it in your Manifest. That way it will share the lifetime of your application.
An additional benefit is that you dont have to worry about unregistering it, so you won't have to worry about memory leaks.
Step 1. Add the JitPack repository to your build file Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Step 2. Add the dependency
dependencies {
implementation 'com.github.SumonHub:EagleEye:1.0.0'
}
If you do not override the Application class, edit your manifest file to set android:name in the tag as follows:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<application
android:name="org.sumon.eagleeye.EagleEyeApplication" >
...
</application>
</manifest>
If you do override the Application class, change it to extend EagleEyeApplication (if possible) as follows:
public class MyApplication extends EagleEyeApplication { ... }
In youre activity/fragment get status like below
EagleEyeObserver.setConnectivityListener(new OnChangeConnectivityListener() {
#Override
public void onChanged(boolean status) {
Toast.makeText(MainActivity.this, "" + status, Toast.LENGTH_SHORT).show();
}
});
more info here
I want to dynamically set up a BroadcastReceiver to check whether or not I am online ONLY when my app is running in the foreground. Within my main class, I created an an Intent Filter, a nested BroadcastReceiver Class and finally register/unregister the receiver within the onResume and onPause methods respectively.
My question is, is there an an intent ACTION that I can add to my intent filter that checks for online connectivity?
If not, how can I create this Dynamic Broadcast Receiver to perform only when my app is running?
Here is what my Class looks like....
public class MainActivity extends AppCompatActivity {
private IntentFilter onlineIntentFilter;
private CheckOnlineReceiver checkOnlineReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onlineIntentFilter = new IntentFilter();
checkOnlineReceiver = new CheckOnlineReceiver();
//*****WHAT INTENT ACTION CAN I PASS TO CHECK NETWORK CONNECTIVITY******
onlineIntentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(checkOnlineReceiver, onlineIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(checkOnlineReceiver);
}
private class CheckOnlineReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Toast.makeText(getApplicationContext(),"IN METHOD, ACTION = " + action, Toast.LENGTH_LONG).show();
}
}}
Add connectivity action
onlineIntentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
and don't forget to add the permission
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
The broadcast receiver's onReceive() will be called on connectivity change which means on both connected and disconnected. so whenever you receive the braodcast you have check for connectivity as below
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
Here is the standard way to do this.
Create a interface which will have two methods onNetworkConnected() and onNetworkDisconnected()
public interface NetworkConnectivityListener {
public void onNetworkConnected();
public void onNetworkDisconnected();
}
Any class that wants to listen to network changes will implement this interface and override it's two methods.
Create a class which will extend the BroadcastReceiver and this receiver's onReceive() will catch the connectivity changes. In this class create a function to register the listeners
public class NetworkBroadcastReceiver extends BroadcastReceiver {
private NetworkConnectivityListener listener;
public NetworkBroadcastReceiver(NetworkConnectivityListener listener) {
this.listener = listener;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (listener != null) {
if (isConnectedToInternet()) {
listener.onNetworkConnected();
} else {
listener.onNetworkDisconnected();
}
}
}
PS you can easily check if your device is connected to internet or not. Just google.
Now let's say you want your MainActivity to listen to netwrork changes, all you have to do is implement the NetworkConnectivityListener in your main activity call and create an instance of the NetworkBroadcastReceiver passing the context of MainActivity and it will start to get the network updates.
add intentfilter CONNECTIVITY_ACTION
You will need to create a service as you are looking to perform a long-running task in the background.
A service will need to be registered in the manifest, within the <application> tags.
<service android:name=".WifiService"
android:stopWithTask="true"
android:enabled="true"/>
stopWithTask causes the service to be destroyed when all of your activities are destroyed (the default value is true).
You will need to register and unregister a BroadcastReceiver to the CONNECTIVITY_CHANGE action in the service class.
public class WifiService extends Service {
private BroadcastReceiver mReceiver;
#Nullable
#Override
public IBinder onBind(Intent intent) {
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
// Your BroadcastReceiver class
mReceiver = new WifiReceiver();
registerReceiver(mReceiver, filter);
return null;
}
#Override
public boolean onUnbind(Intent intent) {
unregisterReceiver(mReceiver);
return super.onUnbind(intent);
}
}
And then in the BroadcastReceiver you must listen for CONNECTIVITY_CHANGE.
public class WifiReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isConnected = networkInfo != null &&
networkInfo.isConnectedOrConnecting();
if (isConnected) {
switch (networkInfo.getType()) {
case ConnectivityManager.TYPE_WIFI:
// Connected via wifi
break;
case ConnectivityManager.TYPE_ETHERNET:
// Connected via ethernet
break;
case ConnectivityManager.TYPE_MOBILE:
// Connected via mobile data
break;
}
}
}
}
With this setup you will be able to notify components of your application on connectivity change.
I have a broadcast to check the network, when the network changes state, I notify my activity with onNetworkActivated() or onNetworkInactivated():
public class NetworkBroadcastReceiver extends BroadcastReceiver
{
private OnNetworkListener currentActivity = null;
public NetworkBroadcastReceiver(FragmentActivity activity)
{
try
{
currentActivity = (OnNetworkListener) activity;
}
catch (ClassCastException e)
{
throw new ClassCastException(activity.toString() + " doit implémenter OnNetworkListener");
}
}
#Override
public void onReceive(Context context, Intent intent)
{
ConnectivityManager connectivity = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null)
{
currentActivity.onNetworkInactivated();
return;
}
else
{
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.getState() == NetworkInfo.State.CONNECTED)
{
currentActivity.onNetworkActivated();
return;
}
}
currentActivity.onNetworkInactivated();
}
public interface OnNetworkListener
{
public void onNetworkActivated();
public void onNetworkInactivated();
}
}
In my Activity, when I I need to call for various reasons sendBroadcast the first time, but Android crash :s
public class Earthquake extends FragmentActivity implements OnNetworkListener
{
private FragmentManager fragmentManager;
private NetworkBroadcastReceiver networkbroadcastreceiver;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fragmentManager = getSupportFragmentManager();
networkbroadcastreceiver = new NetworkBroadcastReceiver(Earthquake.this);
this.registerReceiver(networkbroadcastreceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
this.sendBroadcast(new Intent(ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
protected void onDestroy()
{
this.unregisterReceiver(networkbroadcastreceiver);
super.onDestroy();
}
public void onNetworkActivated()
{
Log.e("onNetworkActivated", "onNetworkActivated");
}
public void onNetworkInactivated()
{
Log.e("onNetworkInactivated", "onNetworkInactivated");
}
}
What is the problem ?
Thank you in advance
https://stackoverflow.com/a/17906435/2201919
By #JoxTraex
You are not allowed to send this broadcast. If applications could send this broadcast then this could cause problems on the device. This is a protected system broadcast.
Please approach your problem in a different way.
Refer: http://developer.android.com/reference/android/net/ConnectivityManager.html
Notice how there are only a few methods that use that action. This implies you cannot send this broadcast.
This question already has answers here:
Check INTENT internet connection
(13 answers)
Closed 4 years ago.
I am making an app where a user is uploading information and files to my server on a somewhat frequent basis. This is done in new threads through a dedicated uploader service.
I know from this thread
Detect whether there is an Internet connection available on Android
that you can check if there is an internet connection relatively easily. You can also get socketTimeoutExceptions to detect internet connectivity issues. All that is well and good, and lets me cache my uploads easily enough when the connection didn't work for whatever reason.
My question though is how do I know when to reattempt the upload? Is there an event triggered when the connection is restored? Or am I stuck making a new thread that sleeps and then checks internet connectivity every 30 seconds or something?
Any ideas would be appreciated!
very old post
but i would like to share my receiver
no need to put your hands on manifest or other boring resources :)
USAGE
YOUR ACTIVITY:
/*
* You need to implement NetworkStateReceiverListener.
* This interface is described inside the NewtworkStateReceiver class
*/
public class MyActivity implements NetworkStateReceiverListener {
/* ... */
private NetworkStateReceiver networkStateReceiver;
}
IN YOUR ACTIVITY: INSTANTIATE THE RECEIVER
public void onCreate(Bundle savedInstanceState) {
/* ... */
networkStateReceiver = new NetworkStateReceiver();
networkStateReceiver.addListener(this);
this.registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
}
public void onDestroy() {
super.onDestroy();
networkStateReceiver.removeListener(this);
this.unregisterReceiver(networkStateReceiver);
}
IN YOUR ACTIVITY: IMPLEMENTS THE REQUIRED METHODS
#Override
public void networkAvailable() {
Log.d("tommydevall", "I'm in, baby!");
/* TODO: Your connection-oriented stuff here */
}
#Override
public void networkUnavailable() {
Log.d("tommydevall", "I'm dancing with myself");
/* TODO: Your disconnection-oriented stuff here */
}
THE RECEIVER
just copy and paste into your project as NetworkStateReceiver.java
public class NetworkStateReceiver extends BroadcastReceiver {
protected Set<NetworkStateReceiverListener> listeners;
protected Boolean connected;
public NetworkStateReceiver() {
listeners = new HashSet<NetworkStateReceiverListener>();
connected = null;
}
public void onReceive(Context context, Intent intent) {
if(intent == null || intent.getExtras() == null)
return;
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = manager.getActiveNetworkInfo();
if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
connected = true;
} else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
connected = false;
}
notifyStateToAll();
}
private void notifyStateToAll() {
for(NetworkStateReceiverListener listener : listeners)
notifyState(listener);
}
private void notifyState(NetworkStateReceiverListener listener) {
if(connected == null || listener == null)
return;
if(connected == true)
listener.networkAvailable();
else
listener.networkUnavailable();
}
public void addListener(NetworkStateReceiverListener l) {
listeners.add(l);
notifyState(l);
}
public void removeListener(NetworkStateReceiverListener l) {
listeners.remove(l);
}
public interface NetworkStateReceiverListener {
public void networkAvailable();
public void networkUnavailable();
}
}
ENJOY ;)
If you just want to do something simple when the connectivity changes, there is a much easier solution.
In your activity, create a Broadcast Receiver:
private BroadcastReceiver networkStateReceiver=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = manager.getActiveNetworkInfo();
doSomethingOnNetworkChange(ni);
}
};
Then in onResume and onPause do the registration:
#Override
public void onResume() {
super.onResume();
registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
public void onPause() {
unregisterReceiver(networkStateReceiver);
super.onPause();
}
Not quite sure what was going on in Tommaso's broadcast receiver but it wasn't working for me, here's my implementation. It only notifies on change between connectivity available/unavailable.
Also I register it in onResume() and unregister in onPause(). Otherwise it's the same as above.
public class NetworkStateReceiver extends BroadcastReceiver {
private ConnectivityManager mManager;
private List<NetworkStateReceiverListener> mListeners;
private boolean mConnected;
public NetworkStateReceiver(Context context) {
mListeners = new ArrayList<NetworkStateReceiverListener>();
mManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
checkStateChanged();
}
public void onReceive(Context context, Intent intent) {
if (intent == null || intent.getExtras() == null)
return;
if (checkStateChanged()) notifyStateToAll();
}
private boolean checkStateChanged() {
boolean prev = mConnected;
NetworkInfo activeNetwork = mManager.getActiveNetworkInfo();
mConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
return prev != mConnected;
}
private void notifyStateToAll() {
for (NetworkStateReceiverListener listener : mListeners) {
notifyState(listener);
}
}
private void notifyState(NetworkStateReceiverListener listener) {
if (listener != null) {
if (mConnected) listener.onNetworkAvailable();
else listener.onNetworkUnavailable();
}
}
public void addListener(NetworkStateReceiverListener l) {
mListeners.add(l);
notifyState(l);
}
public void removeListener(NetworkStateReceiverListener l) {
mListeners.remove(l);
}
public interface NetworkStateReceiverListener {
public void onNetworkAvailable();
public void onNetworkUnavailable();
}
}
Android Nougat & O (API 24+) - Network State
Changes mades to #darnmason answer (constructor) to make it work on API 24+.
public NetworkStateReceiver(Context context) {
mListeners = new ArrayList<>();
mManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(NetworkStateReceiver.this, intentFilter);
checkStateChanged();
}