我想知道我的应用是否已连接到互联网。我的超时设置为3秒。有时互联网检查将返回“未连接”(即使我有互联网连接),有时它不会。为什么有时需要检查的时间比其他人长?在检查这个时,我能够弹出一个对话框或其他东西吗?
public void isNetworkAvailable(final Handler handler)
{
new Thread()
{
private boolean responded = false;
@Override
public void run()
{
new Thread()
{
@Override
public void run()
{
HttpGet requestForTest = new HttpGet("http://m.google.com");
try
{
new DefaultHttpClient().execute(requestForTest);
responded = true;
}
catch (Exception e)
{
}
}
}.start();
try
{
int waited = 0;
while (!responded && (waited < 3000))
{
sleep(100);
if (!responded)
{
waited += 1000;
}
}
}
catch (InterruptedException e)
{
} // do nothing
finally
{
if (!responded)
{
handler.sendEmptyMessage(0);
}
else
{
handler.sendEmptyMessage(1);
}
}
}
}.start();
}
Handler h = new Handler()
{
@Override
public void handleMessage(Message msg)
{
if (msg.what != 1)
{ // code if not connected
Log.i("Internet check", "Not connected");
}
else
{ // code if connected
Log.i("Internet check", "Connected");
}
}
};
答案 0 :(得分:0)
public static Boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if(ni != null && ni.isConnected())
return true;
//Toast.makeText(context, context.getString(R.string.no_internet_connection), Toast.LENGTH_SHORT).show();
return false;
}
需要许可:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
修改强>
正如您所指出的,这不是一个可靠的解决方案。在我的情况下(我确实没有提到),这足以作为与LocationClient.isConnected()配对的第一次检查。
查看您的代码,我认为值得看看LocationClient,即使您不打算使用应用程序的位置感知。
我的理由是你不需要重复使用资源来检查你是否有有效的连接。 LocationClient使用与Google Play的现有通信来告诉您是否已连接。
此解决方案当然只有在您假设您的用户已将Google帐户添加到其设备中时才有效。
以下是官方指南的链接:http://developer.android.com/training/location/retrieve-current.html onConnected和onDisconnected部分可在Define Location Services Callbacks部分找到。
答案 1 :(得分:0)
你考虑使用这个http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html 和 /或注册一个BroadcastReceiver来在连接失败时通知它,然后你可以在你的应用程序的任何地方处理它吗?
public class CustomApplication extends Application {
public static final String INTERNET_ACTION = "internet_action";
public static final String EXTRA_STATUS = "status";
@Override
public void onCreate() {
super.onCreate();
monitorNetworkAvailability();
}
private void monitorNetworkAvailability() {
//
// Improve the way to handle Thread
//
new Thread() {
private boolean responded = false;
@Override
public void run() {
while (true) {
new Thread() {
@Override
public void run() {
HttpGet requestForTest = new HttpGet("http://m.google.com");
try {
new DefaultHttpClient().execute(requestForTest);
responded = true;
} catch (Exception e) {
}
}
}.start();
try {
int waited = 0;
while (!responded && (waited < 3000)) {
sleep(100);
if (!responded) {
waited += 1000;
}
}
} catch (InterruptedException e) {
} // do nothing
finally {
Intent i = new Intent(INTERNET_ACTION);
i.putExtra(EXTRA_STATUS, responded);
sendBroadcast(i);
}
try {
Thread.sleep(1 * 60 * 1000);
} catch (InterruptedException e) {
}
}
}
}.start();
};
}
class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, i);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
IntentFilter i = new IntentFilter(CustomApplication.INTERNET_ACTION);
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean responded = intent.getBooleanExtra(CustomApplication.EXTRA_STATUS, false);
if (!responded) {
Toast.makeText(MyActivity.this, "No connection", Toast.LENGTH_SHORT).show();
}
}
};
}
答案 2 :(得分:0)
使用以下代码
if(!haveInternet()){
<Your Alert Dialog Here>
}
private boolean haveInternet() {
NetworkInfo info = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
return true;
}
return true;
}
答案 3 :(得分:0)
你是对的。您的问题是,设备检查互联网连接,有时从路由器获得响应,表示无法连接到互联网,但这本身就是一个响应,因此您的代码可能会认为存在响应。以下是测试您是否真的可以连接到互联网的示例方法。
public static boolean hasActiveInternetConnection()
{
try
{
new Socket().connect(new InetSocketAddress("google.com", 80), 4000);
return true;
} catch (Exception e)
{
return false;
}
}
然后在你的活动中你可以打电话。 (确保不要在MAIN / UI线程内运行。使用异步或线程/处理程序/可运行策略)
if(hasActiveInternetConnection())
{
//yey I have internet
}
else
{
//no internet connection
}
答案 4 :(得分:0)
我能够通过将其放入AsyncTask来完成此操作。
class online extends AsyncTask<String, String, String>
{
boolean responded = false;
@Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog2 = new ProgressDialog(Main.this);
pDialog2.setMessage("Checking internet, please wait...");
pDialog2.setIndeterminate(false);
pDialog2.setCancelable(false);
pDialog2.show();
}
protected String doInBackground(String... args)
{
HttpGet requestForTest = new HttpGet("http://m.google.com");
try
{
new DefaultHttpClient().execute(requestForTest); // can
responded = true;
}
catch (Exception e)
{
}
try
{
int waited = 0;
while (!responded && (waited < 5000))
{
mHandler.postDelayed(new Runnable()
{
public void run()
{
}
}, 100);
waited += 100;
}
}
finally
{
if (!responded)
{
h.sendEmptyMessage(0);
}
else
{
h.sendEmptyMessage(1);
}
}
return null;
}
protected void onPostExecute(String file_url)
{
pDialog2.dismiss();
}
}