Skip to content

Instantly share code, notes, and snippets.

@VahidHoseini-ir
Created April 23, 2024 13:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VahidHoseini-ir/476a2a16abe041895b32a725cbaf35a4 to your computer and use it in GitHub Desktop.
Save VahidHoseini-ir/476a2a16abe041895b32a725cbaf35a4 to your computer and use it in GitHub Desktop.
یه نمونه استفاده از کلاس broad cast receiver
package com.example.testapp1;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class MBroadcastReceiver extends BroadcastReceiver {
interface StatusInternet {
void getStatus(boolean data);
}
StatusInternet statusInternet;
public MBroadcastReceiver(StatusInternet callBack) {
statusInternet = callBack;
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
if (getInternetStatus(context)) {
statusInternet.getStatus(true);
// Toast.makeText(this, "network is available type mobile data", Toast.LENGTH_SHORT).show();
// textView.setText("network is connected");
} else {
statusInternet.getStatus(false);
// textView.setText("network is not connected to net");
}
}
}
private boolean getInternetStatus(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
return true;
} else if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
}
} else {
return false;
}
return false;
}
}
@VahidHoseini-ir
Copy link
Author

registering in main activity is like :

registerReceiver(new MBroadcastReceiver(this), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment