簡體   English   中英

如何使用onpause和onresume創建活動來瀏覽URL?

[英]How to create activity for browse a url with onpause and onresume?

你能幫我嗎?

如果有Internet連接,如何創建一個在oncreate方法上運行url的活動?

我想檢查Internet連接是否可用,還是每5秒檢查一次,如果Internet連接消失了,它將僅作為Dilog框提醒一次。

如果出現Internet連接,則將在關閉會話的地方恢復活動

在我的代碼下面是:

    public class MainActivity extends Activity {

private String URL="http://www.moneycontrol.com/";

private Handler mHandler = new Handler();

private boolean isRunning = true;

private TextView textlabel=null;    

public WebView webview=null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textlabel=(TextView)findViewById(R.id.textlabel);
        displayData();

    }

    private void Chekstate() {

    new Thread(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (isRunning) {
                try {
                    Thread.sleep(1000);
                    mHandler.post(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            // Write your code here to update the UI.
                            displayData();
                        }
                    });
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        }
    }).start(); 

    }


    @SuppressWarnings("deprecation")
    private void displayData() {
        ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo nf=cn.getActiveNetworkInfo();
        if(nf != null && nf.isConnected()==true )
        {
           textlabel.setText("Network Available");
           Webview();
        }
        else
        {
           textlabel.setText("Network Not Available");
           final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
           alertDialog.setTitle("Intenet Connecction");
           alertDialog.setMessage("Internet Connetion is not available now.");
           alertDialog.setButton(" OK ", new OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                alertDialog.dismiss();
            }
        });
           alertDialog.show();
        }       
    } 


      @Override
        protected void onResume() {
            super.onResume();

        }

        @Override
        protected void onPause() {
            super.onPause();

        }

    @SuppressLint("SetJavaScriptEnabled")
    private void Webview() {
        webview= (WebView) findViewById(R.id.webview);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setWebViewClient(new WebViewClient());
        webview.loadUrl(URL);
        webview.setInitialScale(1);
        webview.getSettings().setBuiltInZoomControls(true);
        webview.getSettings().setUseWideViewPort(true);

    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

要檢查Internet連接,可以使用以下方法。

在清單中添加以下權限

 <uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

使用處理程序

Handler mHandler = new Handler();
boolean isRunning = true;

然后,從您的onCreate()方法使用此線程:

new Thread(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (isRunning) {
                try {
                    Thread.sleep(5000);
                    mHandler.post(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            // Write your code here to update the UI.
                            displayData();
                        }
                    });
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        }
    }).start(); 

然后,聲明此方法,該方法由您的處理程序每​​5秒調用一次:

    private void displayData() {
    ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo nf=cn.getActiveNetworkInfo();
    if(nf != null && nf.isConnected()==true )
    {
        Toast.makeText(this, "Network Available", Toast.LENGTH_SHORT).show();
        myTextView.setText("Network Available");
    }
    else
    {
        Toast.makeText(this, "Network Not Available", Toast.LENGTH_SHORT).show();
        myTextView.setText("Network Not Available");
    }       
} 

要停止線程調用:

   isRunning = false;

或者,您可以使用以下內容。 但是它不會每5秒檢查一次連通性

public class CheckNetwork {
private static final String TAG = CheckNetwork.class.getSimpleName();
public static boolean isInternetAvailable(Context context)
{
NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

if (info == null)
{
     Log.d(TAG,"no internet connection");
     return false;
}
else
{
    if(info.isConnected())
    {
        Log.d(TAG," internet connection available...");
        return true;
    }
    else
    {
        Log.d(TAG," internet connection");
        return true;
    }
   }
 }
}

在您的onCreate()活動中

if(CheckNetwork.isInternetAvailable(MainActivtiy.this))  //if connection available
{

}

http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html

您可以使用BroadCast接收器。 連接斷開時,系統廣播。 但我建議不要使用廣播接收器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM