Я реализовал broadcastReciever
в своем коде следующим образом для динамического получения тоста, когда интернет отключен:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="<MY PACKAGE>">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name=".network.MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".activity.LoginPage"
android:theme="@style/Theme.AppCompat.NoActionBar"
android:windowSoftInputMode="stateHidden|adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".network.ConnectivityReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
</manifest>
MyApplication.java
public class MyApplication extends Application {
private static MyApplication mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) {
ConnectivityReceiver.connectivityReceiverListener = listener;
}
}
BaseActivity.java
public abstract class BaseActivity extends AppCompatActivity implements ConnectivityReceiver.ConnectivityReceiverListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void checkConnection() {
boolean isConnected = ConnectivityReceiver.isConnected();
showSnack(isConnected);
}
public void showSnack(boolean isConnected) {
String message;
int color;
if (isConnected) {
message = "Good! Connected to Internet";
color = Color.WHITE;
} else {
message = "Sorry! Not connected to internet";
color = Color.RED;
}
Toast.makeText(getBaseContext(),message,Toast.LENGTH_LONG).show();
}
@Override
protected void onResume() {
super.onResume();
MyApplication.getInstance().setConnectivityListener(this);
}
@Override
public void onNetworkConnectionChanged(boolean isConnected) {
showSnack(isConnected);
}
}
LoginPage.java
public class LoginPage extends BaseActivity {
Button btnSignin, btnSignup;
EditText etUserEmail, etUserPassword;
ImageView ivViewPassword;
private int mStatusCode;
Boolean flagLogin, flagPass = true;
private RequestQueue mRequestQueue;
ProgressBar pbLoading;
RelativeLayout loadingView, rootlayout_loginPage;
Boolean success = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
init();
testdata();
ivViewPassword.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (flagPass) {
ivViewPassword.setImageResource(R.drawable.ic_hide_password);
etUserPassword.setTransformationMethod(null);
flagPass = false;
} else {
ivViewPassword.setImageResource(R.drawable.ic_show_password);
etUserPassword.setTransformationMethod(new PasswordTransformationMethod());
flagPass = true;
}
}
});
btnSignin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
flagLogin = validateDetails();
if (flagLogin) {
etUserEmail.setError(null);
etUserPassword.setError(null);
loadingView.setVisibility(View.VISIBLE);
pbLoading.setIndeterminate(true);
pbLoading.setVisibility(View.VISIBLE);
}
}
});
btnSignup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), Registration.class);
startActivity(intent);
}
});
}
private void testdata() {
etUserEmail.setText("mncc@example.com");
etUserPassword.setText("1234");
}
private void init() {
btnSignin = (Button) findViewById(R.id.btnSignin);
etUserEmail = (EditText) findViewById(R.id.etUserEmail);
etUserPassword = (EditText) findViewById(R.id.etUserPassword);
ivViewPassword = (ImageView) findViewById(R.id.ivViewPassword);
loadingView = (RelativeLayout) findViewById(R.id.loadingView);
pbLoading = (ProgressBar) findViewById(R.id.pbLoading);
btnSignup = (Button) findViewById(R.id.btnSignup);
rootlayout_loginPage = (RelativeLayout) findViewById(R.id.rootlayout_loginPage);
}
@Override
protected void onResume() {
super.onResume();
MyApplication.getInstance().setConnectivityListener(this);
}
@Override
public void onNetworkConnectionChanged(boolean isConnected) {
showSnack(isConnected);
}
private boolean validateDetails() {
if (etUserEmail.getText().toString().equalsIgnoreCase("")) {
etUserEmail.setError("Email-ID can't be blank!");
etUserEmail.setFocusable(true);
return false;
} else if (!Utils.isValidEmail(etUserEmail.getText().toString())) {
etUserEmail.setError("Invalid Email-ID!");
etUserEmail.setFocusable(true);
return false;
} else if (etUserPassword.getText().toString().equalsIgnoreCase("")) {
etUserPassword.setError("Password can't be blank!");
etUserPassword.setFocusable(true);
return false;
} /*else if (etUserPassword.getText().toString().length() < 8 || etUserPassword.getText().toString().length() > 16) {
etUserPassword.setError("Password must be between 8-16 characters!");
etUserPassword.setFocusable(true);
return false;
}*/ else {
return true;
}
}
Когда я запускаю приложение на своем Android-телефоне или устройстве Android, оно не работает, то есть не показывает тост, когда я переключаю состояние сети или Wi-Fi. Я не могу понять, какую ошибку я совершаю.