代码检查互联网并在连接不存在时关闭应用程序

时间:2013-09-04 13:23:00

标签: android rss

我创建了一个应用程序来读取rss提要,我做了一个启动,我会放入spash,我会设置一个功能来检查你的互联网连接,如果连接存在,应用程序转到活动,读取rss如果不是,那么应用会显示一个弹出窗口,表示连接不存在,并显示关闭应用的按钮。

这是我的SplashActivity的代码

代码:

package rebus.palinsesti.tv;

import rebus.palinsesti.tv.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;

public class SplashActivity extends Activity {

    private static String TAG = SplashActivity.class.getName();
    private static long SLEEP_TIME = 5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.splash);

        IntentLauncher launcher = new IntentLauncher();
        launcher.start();
    }

    private class IntentLauncher extends Thread {

        @Override
        public void run() {
            try {

                Thread.sleep(SLEEP_TIME*1000);
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }

            Intent intent = new Intent(SplashActivity.this, MainActivity.class);
            SplashActivity.this.startActivity(intent);
            SplashActivity.this.finish();
        }
    }

}

2 个答案:

答案 0 :(得分:0)

/**
 * Return Internet connection status
 * @param ctxt
 *      The context
 * @return
 *      True if internet is reachable
 *      False otherwise
 */
public boolean isInternetReachable(Context ctxt)
{
    ConnectivityManager cm = (ConnectivityManager) ctxt.getSystemService(Context.CONNECTIVITY_SERVICE);    
    android.net.NetworkInfo netInfo = cm.getActiveNetworkInfo();    
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

试试这个

希望有所帮助

答案 1 :(得分:0)

    This might help you:

      ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
                // ARE WE CONNECTED TO THE NET
                if (conMgr.getActiveNetworkInfo() != null
                        && conMgr.getActiveNetworkInfo().isAvailable()
                        && conMgr.getActiveNetworkInfo().isConnected()) {
//place the required operation here
    Toast.makeText(this, "net available", Toast.length_duration).show();
     }

    else
    Toast.makeText(this, "net not available", Toast.length_duration).show();