안드로이드 앱에서 인터넷 연결을 확인하기위한 방송 수신기
인터넷 연결을 확인하기 위해 안드로이드 방송 수신기를 개발 중입니다.
문제는 내 방송 수신기가 두 번 호출된다는 것입니다. 네트워크를 사용할 수있을 때만 전화를 걸고 싶습니다. 사용할 수 없으면 알림을 받고 싶지 않습니다.
이것은 방송 수신기입니다
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable() || mobile.isAvailable()) {
// Do something
Log.d("Network Available ", "Flag No 1");
}
}
}
이것이 manifest.xml입니다.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcastreceiverforinternetconnection"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name=".NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
</application>
</manifest>
첫 번째 질문에 대한 답변 : 방송 수신기가 두 번 호출되었습니다.
두 개를 추가했습니다 <intent-filter>
네트워크 연결 변경 :
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
WiFi 상태 변경 :
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
하나만 사용하십시오
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
.
두 가지가 아닌 하나의 작업에만 응답합니다. 자세한 내용은 여기 를 참조하십시오.
두 번째 질문에 답하십시오 (인터넷에 연결되어있는 경우 수신자가 한 번만 전화를 걸기를 원함).
코드는 완벽합니다. 인터넷을 사용할 수있는 경우에만 알립니다.
최신 정보
모바일이 인터넷에 연결되어 있는지 여부를 확인하려는 경우이 방법을 사용하여 연결을 확인할 수 있습니다.
public boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
return (netInfo != null && netInfo.isConnected());
}
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
if(checkInternet(context))
{
Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show();
}
}
boolean checkInternet(Context context) {
ServiceManager serviceManager = new ServiceManager(context);
if (serviceManager.isNetworkAvailable()) {
return true;
} else {
return false;
}
}
}
ServiceManager.java
public class ServiceManager {
Context context;
public ServiceManager(Context base) {
context = base;
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
}
권한 :
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Broadcast Receiver를 사용할 때마다 인터넷 상태 확인 :
Google 드라이브에서 전체 소스 코드를 사용할 수 있습니다 .
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<receiver android:name=".receivers.NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
방송 수신자
package com.keshav.networkchangereceiverexample.receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import static com.keshav.networkchangereceiverexample.MainActivity.dialog;
public class NetworkChangeReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
try
{
if (isOnline(context)) {
dialog(true);
Log.e("keshav", "Online Connect Intenet ");
} else {
dialog(false);
Log.e("keshav", "Conectivity Failure !!! ");
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private boolean isOnline(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
return (netInfo != null && netInfo.isConnected());
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
}
}
MainActivity.java
package com.keshav.networkchangereceiverexample;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import com.keshav.networkchangereceiverexample.receivers.NetworkChangeReceiver;
public class MainActivity extends AppCompatActivity {
private BroadcastReceiver mNetworkReceiver;
static TextView tv_check_connection;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_check_connection=(TextView) findViewById(R.id.tv_check_connection);
mNetworkReceiver = new NetworkChangeReceiver();
registerNetworkBroadcastForNougat();
}
public static void dialog(boolean value){
if(value){
tv_check_connection.setText("We are back !!!");
tv_check_connection.setBackgroundColor(Color.GREEN);
tv_check_connection.setTextColor(Color.WHITE);
Handler handler = new Handler();
Runnable delayrunnable = new Runnable() {
@Override
public void run() {
tv_check_connection.setVisibility(View.GONE);
}
};
handler.postDelayed(delayrunnable, 3000);
}else {
tv_check_connection.setVisibility(View.VISIBLE);
tv_check_connection.setText("Could not Connect to internet");
tv_check_connection.setBackgroundColor(Color.RED);
tv_check_connection.setTextColor(Color.WHITE);
}
}
private void registerNetworkBroadcastForNougat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
protected void unregisterNetworkChanges() {
try {
unregisterReceiver(mNetworkReceiver);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterNetworkChanges();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.keshav.networkchangereceiverexample.MainActivity">
<TextView
android:id="@+id/tv_check_connection"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Connection establised !"
android:padding="25dp"
app:layout_constraintBottom_toBottomOf="parent"
android:gravity="center"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
이 방법을 사용하여 네트워크 상태를 확인하십시오.
private void checkInternetConnection() {
if (br == null) {
br = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
NetworkInfo info = (NetworkInfo) extras
.getParcelable("networkInfo");
State state = info.getState();
Log.d("TEST Internet", info.toString() + " "
+ state.toString());
if (state == State.CONNECTED) {
Toast.makeText(getApplicationContext(), "Internet connection is on", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Internet connection is Off", Toast.LENGTH_LONG).show();
}
}
};
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver((BroadcastReceiver) br, intentFilter);
}
}
onDestroy에서 서비스를 등록 취소해야합니다.
건배!!
public static boolean isNetworkAvailable(Context context) {
boolean isMobile = false, isWifi = false;
NetworkInfo[] infoAvailableNetworks = getConnectivityManagerInstance(
context).getAllNetworkInfo();
if (infoAvailableNetworks != null) {
for (NetworkInfo network : infoAvailableNetworks) {
if (network.getType() == ConnectivityManager.TYPE_WIFI) {
if (network.isConnected() && network.isAvailable())
isWifi = true;
}
if (network.getType() == ConnectivityManager.TYPE_MOBILE) {
if (network.isConnected() && network.isAvailable())
isMobile = true;
}
}
}
return isMobile || isWifi;
}
/* You can write such method somewhere in utility class and call it NetworkChangeReceiver like below */
public class NetworkChangedReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {
if (isNetworkAvailable(context))
{
Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show();
}
}
}
이 브로드 캐스트 수신기는 네트워크 상태가 연결로 변경되고 연결이 끊어지지 않은 경우에만 호출됩니다.
이것으로 시도
public class ConnectionBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (<Check internet connection available >) {
Toast.makeText(context, "connect to the internet", Toast.LENGTH_LONG).show();
/*upload background upload service*/
Intent serviceIntent = new Intent(context,<your service class>);
context.startService(serviceIntent);
}else{
Toast.makeText(context, "Connection faild", Toast.LENGTH_LONG).show();
}
}
}
브로드 캐스트 리시버입니다. 인터넷 연결이 시작 되 자마자로드됩니다
나는이 스레드가 오래되고 완전히 대답했다는 것을 알고 있지만 다음은 일부 사람들에게 도움이 될 수 있다고 생각합니다.
질문 본문의 코드에는 아무도 다루지 않은 버그가 포함되어 있습니다. @Nikhil은 Wi-Fi / 모바일이 연결되어 있는지 여부를 확인합니다.
수정 사항은 다음과 같습니다.
@Override
public void onReceive(final Context context, final Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isConnected() || mobile.isConnected()) {
// do stuff
}
}
명백한:
<receiver android:name=".your.namepackage.here.ConnectivityReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
수신기 클래스 :
public class ConnectivityReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
switch (action) {
case ConnectivityManager.CONNECTIVITY_ACTION:
DebugUtils.logDebug("BROADCAST", "network change");
if(NetworkUtils.isConnect()){
//do action here
}
break;
}
}
}
예제와 같은 클래스 유틸리티 :
public class NetworkUtils {
public static boolean isConnect() {
ConnectivityManager connectivityManager = (ConnectivityManager) Application.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Network[] netArray = connectivityManager.getAllNetworks();
NetworkInfo netInfo;
for (Network net : netArray) {
netInfo = connectivityManager.getNetworkInfo(net);
if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) {
//if (netInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName());
return true;
}
}
} else {
if (connectivityManager != null) {
@SuppressWarnings("deprecation")
NetworkInfo[] netInfoArray = connectivityManager.getAllNetworkInfo();
if (netInfoArray != null) {
for (NetworkInfo netInfo : netInfoArray) {
if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) {
//if (netInfo.getState() == NetworkInfo.State.CONNECTED) {
Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName());
return true;
}
}
}
}
}
return false;
}
}
방송을 동적으로 등록하려는 다른 사람을 위해 :
BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (checkWifiConnect()) {
Log.d(TAG, "wifi has connected");
// TODO
}
}
};
private void registerWifiReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
mContext.registerReceiver(mWifiReceiver, filter);
}
private void unregisterWifiReceiver() {
mContext.unregisterReceiver(mWifiReceiver);
}
private boolean checkWifiConnect() {
ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo != null
&& networkInfo.getType() == ConnectivityManager.TYPE_WIFI
&& networkInfo.isConnected()) {
return true;
}
return false;
}
Android 7.0 (API 레벨 24) 이상을 대상으로하는 앱은 매니페스트에서 브로드 캐스트 수신기를 선언하면이 브로드 캐스트를받지 않습니다. 앱이 Context.registerReceiver ()에 BroadcastReceiver를 등록하고 해당 컨텍스트가 여전히 유효한 경우에도 여전히 브로드 캐스트를 수신합니다.
public class AsyncCheckInternet extends AsyncTask<String, Void, Boolean> {
public static final int TIME_OUT = 10 * 1000;
private OnCallBack listener;
public interface OnCallBack {
public void onBack(Boolean value);
}
public AsyncCheckInternet(OnCallBack listener) {
this.listener = listener;
}
@Override
protected void onPreExecute() {
}
@Override
protected Boolean doInBackground(String... params) {
ConnectivityManager connectivityManager = (ConnectivityManager) General.context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if ((networkInfo != null && networkInfo.isConnected())
&& ((networkInfo.getType() == ConnectivityManager.TYPE_WIFI) || (networkInfo
.getType() == ConnectivityManager.TYPE_MOBILE))) {
HttpURLConnection urlc;
try {
urlc = (HttpURLConnection) (new URL("http://www.google.com")
.openConnection());
urlc.setConnectTimeout(TIME_OUT);
urlc.connect();
if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) {
return true;
} else {
return false;
}
} catch (MalformedURLException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
} else {
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
if (listener != null) {
listener.onBack(result);
}
}
}
네트워크 연결 변경을 청취 할 수있는 브로드 캐스트 수신기를 추가하십시오. 그런 다음 장치가 인터넷에 연결되어 있는지 또는 ConnectivityManager를 사용하고 있지 않은지 확인하십시오. 자세한 내용은이 게시물 또는 비디오 를 참조하십시오 . 코드는 다음과 같습니다.
public class NetworkStateChangeReceiver extends BroadcastReceiver {
public static final String NETWORK_AVAILABLE_ACTION = "com.ajit.singh.NetworkAvailable";
public static final String IS_NETWORK_AVAILABLE = "isNetworkAvailable";
@Override
public void onReceive(Context context, Intent intent) {
Intent networkStateIntent = new Intent(NETWORK_AVAILABLE_ACTION);
networkStateIntent.putExtra(IS_NETWORK_AVAILABLE, isConnectedToInternet(context));
LocalBroadcastManager.getInstance(context).sendBroadcast(networkStateIntent);
}
private boolean isConnectedToInternet(Context context) {
try {
if (context != null) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
return false;
} catch (Exception e) {
Log.e(NetworkStateChangeReceiver.class.getName(), e.getMessage());
return false;
}
}
}
화면에 알림을 표시하기 위해이 수신기를 썼기 때문에 네트워크 상태의 로컬 브로드 캐스트가 표시됩니다. 알림을 표시하는 코드는 다음과 같습니다.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter intentFilter = new IntentFilter(NetworkStateChangeReceiver.NETWORK_AVAILABLE_ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean isNetworkAvailable = intent.getBooleanExtra(IS_NETWORK_AVAILABLE, false);
String networkStatus = isNetworkAvailable ? "connected" : "disconnected";
Snackbar.make(findViewById(R.id.activity_main), "Network Status: " + networkStatus, Snackbar.LENGTH_LONG).show();
}
}, intentFilter);
}
}
활동은 네트워크 수신기가 브로드 캐스트 한 의도를 듣고 화면에 알림을 표시합니다.
활동, 조각 또는 상황에 맞는 편안한 방법이 있습니다. 원하는 경우 활동 / 조각 (onDestroy에서)을 위해 수행하면 자동 등록 취소됩니다.
abstract class ConnectionBroadcastReceiver : BroadcastReceiver() {
companion object {
@JvmStatic
fun registerWithoutAutoUnregister(context: Context, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
context.registerReceiver(connectionBroadcastReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
}
@JvmStatic
fun registerToFragmentAndAutoUnregister(context: Context, fragment: Fragment, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
val applicationContext = context.applicationContext
registerWithoutAutoUnregister(applicationContext, connectionBroadcastReceiver)
fragment.lifecycle.addObserver(object : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
applicationContext.unregisterReceiver(connectionBroadcastReceiver)
}
})
}
@JvmStatic
fun registerToActivityAndAutoUnregister(activity: AppCompatActivity, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
registerWithoutAutoUnregister(activity, connectionBroadcastReceiver)
activity.lifecycle.addObserver(object : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
activity.unregisterReceiver(connectionBroadcastReceiver)
}
})
}
@JvmStatic
fun hasInternetConnection(context: Context): Boolean {
val info = (context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
return !(info == null || !info.isConnectedOrConnecting)
}
}
override fun onReceive(context: Context, intent: Intent) {
val hasConnection = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)
// Log.d("AppLog", "conenctivity changed. hasConnection? $hasConnection")
onConnectionChanged(hasConnection)
}
abstract fun onConnectionChanged(hasConnection: Boolean)
}
조각으로 사용법 :
ConnectionBroadcastReceiver.registerToFragmentAndAutoUnregister(activity!!, this, object : ConnectionBroadcastReceiver() {
override fun onConnectionChanged(hasConnection: Boolean) {
// Log.d("AppLog", "onConnectionChanged:" + hasConnection)
}
})
인터넷 연결 변경을 확인하기위한 브로드 캐스트 수신기 코드 :
public class BroadCastDetecter extends BroadcastReceiver {
public static boolean internet_status = false;
public static void checkInternetConenction(Context context) {
internet_status = false;
ConnectivityManager check = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (check != null) {
NetworkInfo[] info = check.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
{
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
internet_status = true;
}
}
if(internet_status)
{
//do what you want to if internet connection is available
}
}
}
@Override
public void onReceive(Context context, Intent intent)
{
try {
checkInternetConenction(context);
}catch(Exception e){
}
}
}
매니페스트 파일에 이것을 추가하십시오 :
<receiver android:name=".BroadCastDetecter">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
이것은 네트워크 인터페이스가 사용 가능한지 확인하고 특정 네트워크 서비스가 사용 가능한지 보장하지 않습니다 (예 : 신호가 낮거나 서버 다운 타임이있을 수 있음)
private boolean isNetworkInterfaceAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
연결이 서버 또는 URL에서 데이터를 수집 할 수 있도록 실제 연결을 원할 경우 :
private boolean isAbleToConnect(String url, int timeout) {
try {
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(timeout);
connection.connect();
return true;
} catch (Exception e) {
Log.i("exception", "" + e.getMessage());
return false;
}
}
이 함수는 백그라운드 스레드로 싸야합니다.
final String action = intent.getAction();
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
checkConnectivity(context);
}
}
private void checkConnectivity(final Context context) {
if (!isNetworkInterfaceAvailable(context)) {
Toast.makeText(context, "You are OFFLINE!", Toast.LENGTH_SHORT).show();
return;
}
final Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
final boolean isConnected = isAbleToConnect("http://www.google.com", 1000);
handler.post(new Runnable() {
@Override
public void run() {
if (isConnected)
Toast.makeText(context, "You are ONLINE!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(context, "You are OFFLINE!", Toast.LENGTH_SHORT).show();
}
});
}
}).start();
}
필요한 권한을 추가하십시오.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
매니페스트 파일의 응용 프로그램 아래에 다음 줄을 추가하십시오.
android:usesCleartextTraffic="true"
매니페스트 파일에 수신자 추가 :
<receiver android:name=".ConnectivityChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
활동에서 BR 등록 / 등록 취소 :
@Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(connectivityChangeReceiver, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(connectivityChangeReceiver);
}
이것은 전체 브로드 캐스트 클래스입니다.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import java.net.URL;
import java.net.URLConnection;
public class ConnectivityChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
final String action = intent.getAction();
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
checkConnectivity(context);
}
}
private void checkConnectivity(final Context context) {
if (!isNetworkInterfaceAvailable(context)) {
Toast.makeText(context, "You are OFFLINE!", Toast.LENGTH_SHORT).show();
return;
}
final Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
final boolean isConnected = isAbleToConnect("http://www.google.com", 1000);
handler.post(new Runnable() {
@Override
public void run() {
if (isConnected)
Toast.makeText(context, "You are ONLINE!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(context, "You are OFFLINE!", Toast.LENGTH_SHORT).show();
}
});
}
}).start();
}
//This only checks if the network interface is available, doesn't guarantee a particular network service is available, for example, there could be low signal or server downtime
private boolean isNetworkInterfaceAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
//This makes a real connection to an url and checks if you can connect to this url, this needs to be wrapped in a background thread
private boolean isAbleToConnect(String url, int timeout) {
try {
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(timeout);
connection.connect();
return true;
} catch (Exception e) {
Log.i("exception", "" + e.getMessage());
return false;
}
}
}
https://github.com/JobGetabu/DroidNet 을 사용하는 것이 더 쉽습니다.
@Override
public void onInternetConnectivityChanged(boolean isConnected) {
if (isConnected) {
//do Stuff with internet
netIsOn();
} else {
//no internet
netIsOff();
}
}
private void netIsOn(){...}
private void netIsOff(){...}
우선 네트워크 상태의 연결을 확인하는 클래스를 만듭니다. 클래스를 만들자.
public class AppStatus {
private static AppStatus instance = new AppStatus();
static Context context;
ConnectivityManager connectivityManager;
NetworkInfo wifiInfo, mobileInfo;
boolean connected = false;
public static AppStatus getInstance(Context ctx) {
context = ctx.getApplicationContext();
return instance;
}
public boolean isOnline() {
try {
connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
connected = networkInfo != null && networkInfo.isAvailable() &&
networkInfo.isConnected();
return connected;
} catch (Exception e) {
System.out.println("CheckConnectivity Exception: " + e.getMessage());
Log.v("connectivity", e.toString());
}
return connected;
}
}
이제 새로운 방송 수신기 클래스를 만드십시오.
public class ConnectivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (AppStatus.getInstance(context).isOnline()) {
Intent intent1=new Intent(context,DisplayAct.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent1);
} else {
Toast.makeText(context, "Please !! Make your network ON", Toast.LENGTH_SHORT).show();
}
}
}
이제 브로드 캐스트 수신기를 매니페스트에 등록하십시오.
<receiver android:name=".ConnectivityReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
'IT story' 카테고리의 다른 글
Java에서 바이트 리터럴을 어떻게 지정합니까? (0) | 2020.04.23 |
---|---|
C에서 함수 포인터의 typedef 이해 (0) | 2020.04.23 |
JavaScript % (모듈로)는 음수에 대해 음수 결과를 제공합니다. (0) | 2020.04.23 |
Assert.Throws를 사용하여 예외 유형을 지정하려면 어떻게합니까? (0) | 2020.04.23 |
Html.ActionLink를 사용하여 다른 컨트롤러에서 작업 호출 (0) | 2020.04.23 |