简体   繁体   English

如何使用onpause和onresume创建活动来浏览URL?

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

Can you please help me on this? 你能帮我吗?

How to create a activity which runs a url at oncreate method if Internet connection is available? 如果有Internet连接,如何创建一个在oncreate方法上运行url的活动?

I want to check Internet connection is available or not every 5 seconds, if Internet connection gone it will alert as dilog box only one time. 我想检查Internet连接是否可用,还是每5秒检查一次,如果Internet连接消失了,它将仅作为Dilog框提醒一次。

If Internet connection comes then activty will resume where the session was closed 如果出现Internet连接,则将在关闭会话的地方恢复活动

Here below my code is: 在我的代码下面是:

    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;
    }

}

to check internet connectivity you can use the following. 要检查Internet连接,可以使用以下方法。

Add the following permissions in manifest 在清单中添加以下权限

 <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"/>

Use a handler 使用处理程序

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

Then, use this thread from your onCreate() method : 然后,从您的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(); 

Then, declare this method which called by your handler at every 5 seconds : 然后,声明此方法,该方法由您的处理程序每​​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");
    }       
} 

To stop thread call this : 要停止线程调用:

   isRunning = false;

Alterntively you ca use the below. 或者,您可以使用以下内容。 But it does not check connectivty every 5 seonds 但是它不会每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;
    }
   }
 }
}

In your activity in onCreate() 在您的onCreate()活动中

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

}

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

You can use a BroadCast Reciever. 您可以使用BroadCast接收器。 When connectivity is lost the system broadcasts. 连接断开时,系统广播。 But i suggest not to use broadcast reciever. 但我建议不要使用广播接收器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM