这不是重复的
如果有可用连接,我想使用activity
和AsyncTask
检查Handler
的实时互联网连接,以显示或隐藏TexView
。但它不起作用。
我的代码即使使用AsyncTask
也会抛出NetworkOnMainThreadException
我正在使用此代码:
class CheckNetWorkConnection extends AsyncTask<String, Void,Boolean>{
MyActivity activity;
public checkNetWorkConnection(MyActivity activity) {
this.activity= activity;
}
@Override
protected Boolean doInBackground(String... strings) {
boolean networkAvalaible;
try {
URL myUrl = new URL("https://www.stackoverflow.com");
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
networkAvalaible = true;
} catch (Exception e) {
//I'm catching NetworkInMainThreadException here
e.printStackTrace();
networkAvalaible = false;
}
}
});
// doInBackground always retun false
return networkAvalaible;
}
@Override
protected void onPostExecute(Boolean aBoolean) {
// Using handler to repeat Task
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (aBoolean){
activity.noConnection.setVisibility(View.GONE);
}else {
activity.noConnection.setVisibility(View.VISIBLE);
}
}
},3000);
super.onPostExecute(aBoolean);
}
}
答案 0 :(得分:0)
使用它,你打电话
new CheckNetWorkConnection().execute();
您将希望您的异步任务无限期运行,直到互联网连接丢失。您当前的代码只会检查一次。
您需要更改代码以进行轮询以使其正常工作。
@Override
protected Boolean doInBackground(String... strings) {
boolean networkAvalaible = false;
do {
try {
URL myUrl = new URL("https://www.stackoverflow.com");
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
networkAvalaible = true;
sleep(5000); //check connection every 5 seconds.
// you can call publish progress here to tell your process that
// connection is available
} catch (Exception e) {
//I'm catching NetworkInMainThreadException here
e.printStackTrace();
networkAvalaible = false;
}
} while (networkAvalaible);
//you only exit and asyncTask when connection is lost.
return networkAvalaible;
}
虽然AsyncTask不是正确的方法...但请看下面的以下文章。 https://www.grokkingandroid.com/android-getting-notified-of-connectivity-changes/
答案 1 :(得分:0)
将此类放入 util 包中,以便在您项目的任何位置查看互联网连接。
<强> ConnectionDetector.java 强>
package util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* Created by Pranav on 29/08/16.
*/
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
}
以下是 MainActivity.java 检查互联网连接的代码段,如果互联网连接已开启,则调用asynctask,否则会提供Toast消息。
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import java.net.URL;
import java.net.URLConnection;
import util.ConnectionDetector;
/**
* Created by Pranav on 29/08/16.
*/
public class CaseDetaiksActivity extends Activity {
public static Context context;
ConnectionDetector mConnectionDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
mConnectionDetector = new ConnectionDetector(context);
setContentView(R.layout.activity_mail);
if (mConnectionDetector.isConnectingToInternet()) {
MyAyncTask MyTask = new MyAyncTask();
MyTask.execute();
} else {
Toast.makeText(context, getString(R.string.please_check_internet), Toast.LENGTH_SHORT).show();
}
}
public static class MyAyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
// You can track you progress update here
}
@Override
protected Void doInBackground(Void... params) {
try {
URL myUrl = new URL("https://www.stackoverflow.com");
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
} catch (Exception e) {
//I'm catching NetworkInMainThreadException here
e.printStackTrace();
}
return null;
}
}
}
希望这有助于你
答案 2 :(得分:0)
a。创建广播接收器类
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();
}
}
public boolean checkInternet(Context context) {
ServiceManager serviceManager = new ServiceManager(context);
if (serviceManager.isNetworkAvailable()) {
return true;
} else {
return false;
}
}
}
湾创建服务管理器类
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();
}
}
在Android清单中注册权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
在Android清单中声明广播接收器
<receiver android:name=".receivers.NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
在您的活动中:
一个。在onResume()
中注册您的广播接收器 registerReceiver(new NetworkChangeReceiver() , new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
湾在onPause();
中取消注册您的广播接收器 unregisterReceiver(new NetworkChangeReceiver());