Android
안드로이드(Android) 웹뷰(WebView) 인터넷연결 상태 체크하여 알림창 띄우기
일용직 코딩노동자
2020. 2. 21. 15:07
728x90
반응형
Webview를 이용하는동안 데이터가 소진된다거나 와이파이 끊어져서 인터넷이 응답하지않는 경우에 사용해봅니다.
mWebView.setWebViewClient(new SslWebViewConnect(){
@Override
public void onReceivedError(final WebView view, int errorCode, String description, final String failingUrl) {
mWebView.removeView(view);
mWebView.destroy();
Intent intent = new Intent(getApplicationContext(),NetworkNotConnectionActivity.class);
startActivity(intent);
super.onReceivedError(view, errorCode, description, failingUrl);
}
});
onCreate안에 넣어줍니다.
mWebView는 저의 웹뷰 정의 이름이므로 정의하신 이름으로 넣으시기바랍니다.
removeView와 destory가 없으면 웹페이지 에러창이 보이고 Intent가 실행되기때문에 웹뷰를 바로 종료해줍니다.
다음은 NetworkNotConnectionActivity 클래스입니다.
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class NetworkNotConnectionActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.network);
AlertDialog.Builder alert_confirm = new AlertDialog.Builder(NetworkNotConnectionActivity.this);
alert_confirm.setMessage("네트워크 연결이 원활하지 않습니다\n모바일데이터 및 WIFI 연결상태를 확인해주세요.");
alert_confirm.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
});
AlertDialog alert = alert_confirm.create();
alert.setIcon(R.drawable.icon);
alert.setTitle("알 림");
alert.show();
}
}
이러면 중간에 인터넷 연결이 끊어진다면 NetworkNotConnectionActivity 클래스로 넘어와서
network라는 하얀색 빈 Activity화면을 보여줍니다.
network레이아웃은 그냥 하얀색 빈 화면으로 구성하시면 됩니다.
그리고 바로 다이얼로그창을 띄워서 보여줍니다.
확인버튼을 누를 시 다시 MainAcitvity로 이동합니다.
만약 이동했는데도 인터넷이 연결이 되지않았다면 다시 onReceivedError오버라이드를 탈것입니다.
그럼 다시 NetworkNotConnectionActivity 로 이동합니다.
인터넷 연결이 됬다면 정상적으로 다시 MainAcvity가 가동됩니다.
도움이 되셨다면 하트와 궁금하신 사항은 댓글을 남겨주세요.
728x90
반응형