通过检查这里的一些问题,我设法创建了下面的类,以检查用户是否有活动的互联网连接。我想在我的Android活动中使用它来检查连接,然后我从互联网上加载任何数据。我想问一下这是否是检查用户互联网连接的合适方式,我希望有人提供一个如何从活动中调用它的示例(如何将上下文传递给它以及如何获取{ {1}}回复我的Android活动。
true/false
答案 0 :(得分:0)
我会在异步任务之外获取网络信息,因为您可以更轻松地处理如何对给定的网络状态做出反应。
对于Async Task,您可以将其设置为Activity的内部类,并在调用Async Task的execute方法之前检查网络状态。
public class MyActivity extends Activity{
...
...
private static boolean isNetworkAvailable(Context c) {
NetworkInfo netInfo = null;
try {
ConnectivityManager cm = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
netInfo = cm.getActiveNetworkInfo();
} catch (SecurityException e) {
e.printStackTrace();
// Something bad happen, better return false.
return false;
}
return netInfo != null && netInfo.isConnectedOrConnecting();
}
//Let's assume you will call your data from the internet like this
private void getDataFromTheInternet(){
if (isNetworkAvailable){
ConnectionStatus cStatus = new ConnectionStatus(getApplicationContext());
cStatus.execute();
}else{
//Prevent the user that there is not a network connection
}
}
现在,从Asynk Task中删除isNetworkAvailable方法,然后你去。
此外,您可以使用BroadCast接收器在每次连接状态发生变化时进行检查,以便您的应用程序在离线或联机后可以做出反应tutorial
答案 1 :(得分:0)
以下是包含AsyncTask的Activity类的示例,并展示了如何在更新版本的问题中使用ConnectionStatus
类。
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text);
//Create Strings to pass to varargs of AsyncTask
String s1 = "test1";
String s2 = "test2";
new MyAsync().execute(s1, s2);
}
class MyAsync extends AsyncTask<String, String, String> {
ConnectionStatus status;
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... params) {
String retVal = null;
//Instantiate your object, use MainActivity.this for Context
status = new ConnectionStatus(MainActivity.this);
//capture varargs
String sOne = params[0];
String sTwo = params[1];
boolean something = false;
//Check network connectivity:
if (status.CheckConnection()){
//You have internet, do your network operations here
//...............
//Just here for an example:
if (something == true){
retVal = sOne;
}
else{
retVal = sTwo;
}
}
return retVal;
}
@Override
protected void onPostExecute(String arg) {
//Update UI here, this runs on the Main UI thread of the Activity
if (arg != null){
textView.setText(arg);
}
}
}
}