Created
April 23, 2024 13:12
-
-
Save VahidHoseini-ir/476a2a16abe041895b32a725cbaf35a4 to your computer and use it in GitHub Desktop.
یه نمونه استفاده از کلاس broad cast receiver
This file contains 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
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
registering in main activity is like :
registerReceiver(new MBroadcastReceiver(this), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));