广播接收器和互联网连接

发布于 2024-12-01 04:51:59 字数 4984 浏览 0 评论 0原文

如何使用广播接收器检查是否没有互联网连接?

之后:

1.如果有连接 = 不执行任何操作

2.没有连接 = 打开新活动

我希望您明白我在问什么。

这是我的 webview 应用程序代码:

WebView mWebView;
    String URL = "http://url.com";
    ProgressBar loadingProgressBar,loadingTitle;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);


        mWebView = (WebView) findViewById(R.id.Web);
        mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.loadUrl(URL);
        mWebView.setWebViewClient(new MyWebViewClient());

        loadingProgressBar=(ProgressBar)findViewById(R.id.progressBar); 

        mWebView.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
        super.onProgressChanged(view, newProgress);
        loadingProgressBar.setProgress(newProgress);
        if (newProgress == 100) {
        loadingProgressBar.setVisibility(View.GONE);
        } else{
        loadingProgressBar.setVisibility(View.VISIBLE);
        }
        }
        });
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


        private class MyWebViewClient extends WebViewClient {


      @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url) {
          if (url.endsWith(".mp3")) {
              Intent intent = new Intent(Intent.ACTION_VIEW);
              intent.setDataAndType(Uri.parse(url), "audio/*");
              view.getContext().startActivity(intent);   
              return true;
          } else if (url.endsWith(".mp4") || url.endsWith(".3gp")) {
                  Intent intent = new Intent(Intent.ACTION_VIEW); 
                  intent.setDataAndType(Uri.parse(url), "video/*");
                  view.getContext().startActivity(intent);   
                  return true;
          } else {
              return super.shouldOverrideUrlLoading(view, url);
          }
        }
      }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
  case R.id.menu_paivita:
    mWebView.reload();
    return true;
  case R.id.menu_sulje:
    a.this.finish();
    return true;
  case R.id.menu_tietoa:
          Intent intent = new Intent(a.this, c.class);
          intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          startActivity(intent);
         return true;
  case R.id.menu_palautetta:
      Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
      String aEmailList[] = { "[email protected]" };
      emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, aEmailList);
      emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Palaute Sovelluksesta");
      emailIntent.setType("plain/text");
      startActivity(Intent.createChooser(emailIntent, "Send your email in: Gmail"));
      return true;
    default:
        return false;
}
}
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
        String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
                    boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

        NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
        NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

        // do application-specific task(s) based on the current network state, such
        // as enabling queuing of HTTP requests when currentNetworkInfo is connected etc.
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info != null) {
            if (!info.isConnected()) {
            }
        }
        else {
            setContentView(R.layout.connection_error);
        }
    }
};

感谢您的帮助!

更新:代码已更新!

How do I use broadcast receiver to check if there isn't Internet connection?

And after that:

1.If there is connection = do nothing

2.There isn't connection = open new activity

I hope you understand what I'm asking about.

Here is my webview app code:

WebView mWebView;
    String URL = "http://url.com";
    ProgressBar loadingProgressBar,loadingTitle;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);


        mWebView = (WebView) findViewById(R.id.Web);
        mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.loadUrl(URL);
        mWebView.setWebViewClient(new MyWebViewClient());

        loadingProgressBar=(ProgressBar)findViewById(R.id.progressBar); 

        mWebView.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
        super.onProgressChanged(view, newProgress);
        loadingProgressBar.setProgress(newProgress);
        if (newProgress == 100) {
        loadingProgressBar.setVisibility(View.GONE);
        } else{
        loadingProgressBar.setVisibility(View.VISIBLE);
        }
        }
        });
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


        private class MyWebViewClient extends WebViewClient {


      @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url) {
          if (url.endsWith(".mp3")) {
              Intent intent = new Intent(Intent.ACTION_VIEW);
              intent.setDataAndType(Uri.parse(url), "audio/*");
              view.getContext().startActivity(intent);   
              return true;
          } else if (url.endsWith(".mp4") || url.endsWith(".3gp")) {
                  Intent intent = new Intent(Intent.ACTION_VIEW); 
                  intent.setDataAndType(Uri.parse(url), "video/*");
                  view.getContext().startActivity(intent);   
                  return true;
          } else {
              return super.shouldOverrideUrlLoading(view, url);
          }
        }
      }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
  case R.id.menu_paivita:
    mWebView.reload();
    return true;
  case R.id.menu_sulje:
    a.this.finish();
    return true;
  case R.id.menu_tietoa:
          Intent intent = new Intent(a.this, c.class);
          intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          startActivity(intent);
         return true;
  case R.id.menu_palautetta:
      Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
      String aEmailList[] = { "[email protected]" };
      emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, aEmailList);
      emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Palaute Sovelluksesta");
      emailIntent.setType("plain/text");
      startActivity(Intent.createChooser(emailIntent, "Send your email in: Gmail"));
      return true;
    default:
        return false;
}
}
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
        String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
                    boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

        NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
        NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

        // do application-specific task(s) based on the current network state, such
        // as enabling queuing of HTTP requests when currentNetworkInfo is connected etc.
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info != null) {
            if (!info.isConnected()) {
            }
        }
        else {
            setContentView(R.layout.connection_error);
        }
    }
};

Thanks for your help!

UPDATE: Code is updated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦开始←不甜 2024-12-08 04:51:59

ConnectivityManager 提供了您可以检查的调用用于互联网连接。

如果您想监听连接的变化,请创建一个对 ConnectivityManager.CONNECTIVITY_ACTION

ConnectivityManager provides calls by which you can check for internet connectivity.

If you want to listen for a change in connectivity, create a listener that reacts to ConnectivityManager.CONNECTIVITY_ACTION

梦幻之岛 2024-12-08 04:51:59

在您的项目中创建一个文件...,并将以下代码复制粘贴到该文件中

package your.package.name; //Change it as your package name

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

public class NetworkChangeReceiver extends BroadcastReceiver {

    public static int TYPE_WIFI = 1;
    public static int TYPE_MOBILE = 2;
    public static int TYPE_NOT_CONNECTED = 0;

    @Override
    public void onReceive(final Context context, final Intent intent) {

        String status = getConnectivityStatusString(context);

        Toast.makeText(context, status, Toast.LENGTH_LONG).show();
    }

    public static int getConnectivityStatus(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork) {
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                return TYPE_WIFI;

            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                return TYPE_MOBILE;
        } 
        return TYPE_NOT_CONNECTED;
    }

    public static String getConnectivityStatusString(Context context) {
        int conn = getConnectivityStatus(context);
        String status = null;
        if (conn == TYPE_WIFI) {
        status = "Wifi enabled";
        } else if (conn == TYPE_MOBILE) {
            status = "Mobile data enabled";
        } else if (conn == TYPE_NOT_CONNECTED) {
            status = "Not connected to Internet";
        }
        return status;
    }
}

,并将以下代码添加到应用程序标签中的清单文件中。

<application  ...>
 ...
    <receiver
        android:name="your.package.name.NetworkChangeReceiver" //Change it as your-package-name.NetworkChangeReceiver
        android:label="NetworkChangeReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
        </intent-filter>
    </receiver>
  ...
</application>

运行应用程序后,如果网络状态发生变化,您将看到 Toast 消息。

Create a file to your project as ... and copy paste following code into this file

package your.package.name; //Change it as your package name

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

public class NetworkChangeReceiver extends BroadcastReceiver {

    public static int TYPE_WIFI = 1;
    public static int TYPE_MOBILE = 2;
    public static int TYPE_NOT_CONNECTED = 0;

    @Override
    public void onReceive(final Context context, final Intent intent) {

        String status = getConnectivityStatusString(context);

        Toast.makeText(context, status, Toast.LENGTH_LONG).show();
    }

    public static int getConnectivityStatus(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork) {
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                return TYPE_WIFI;

            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                return TYPE_MOBILE;
        } 
        return TYPE_NOT_CONNECTED;
    }

    public static String getConnectivityStatusString(Context context) {
        int conn = getConnectivityStatus(context);
        String status = null;
        if (conn == TYPE_WIFI) {
        status = "Wifi enabled";
        } else if (conn == TYPE_MOBILE) {
            status = "Mobile data enabled";
        } else if (conn == TYPE_NOT_CONNECTED) {
            status = "Not connected to Internet";
        }
        return status;
    }
}

And add following to Manifest file in application tag

<application  ...>
 ...
    <receiver
        android:name="your.package.name.NetworkChangeReceiver" //Change it as your-package-name.NetworkChangeReceiver
        android:label="NetworkChangeReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
        </intent-filter>
    </receiver>
  ...
</application>

After running your application you will see Toast Message if network state change.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文