How to interpret whether the current device is connected to the network in Android development

Source: Internet
Author: User
Tags getcolor sqlite database

1: Preface:

We are in the process of Android development, many of the implementation is to the remote server to take data, but not necessarily the current device must be connected to the network Ah, so at this time we are to make judgments,

If there is a network, then go to the remote server to get data, if there is no network, give users a small warm hint, at the same time for the user's experience friendly, no network

You can take the data to the local SQLite database area. (when there is a network, the data of the SQLite database needs to be updated immediately).

Now we start to demonstrate how to determine whether the current device is connected to the network.

2:new a Android Android project

The code in the default activity is as follows. [We make a button to trigger the event, and a text to display the current network data information]

1  PackageCom.example.androidtestwangluo;2 3 Importandroid.app.Activity;4 ImportAndroid.os.Bundle;5 ImportAndroid.widget.Button;6 7 8  Public classMainactivityextendsActivity {9 Ten     PrivateButton mybtn; One @Override A     protected voidonCreate (Bundle savedinstancestate) { -         Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); the          -          //The control that makes the bind button -MYBTN =(Button) Findviewbyid (R.id.mybutton); -          +           //An instance of an event class is required to listen for an event that is tied to an order. (We make a definition on the outside) -Mybtn.setonclicklistener (NewMyonclickliner ( This)); +          A          at     } -}

At this point the activity corresponds to the-----------"layout"-----code XML for the settings as follows

Next, let's take a look at that. The code for the implementation class of the event after clicking Event New Myonclickliner ( this) is this class Myonclickliner

 PackageCom.example.androidtestwangluo;Importandroid.app.Activity;ImportAndroid.content.Context;ImportAndroid.net.ConnectivityManager;ImportAndroid.net.NetworkInfo;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.TextView;ImportAndroid.widget.Toast; Public classMyonclicklinerImplementsOnclicklistener {Privatecontext Context; PrivateTextView Thistext; //Define a connection regulatory object    PrivateConnectivitymanager cm;  PublicMyonclickliner (Context context) { This. ConText =ConText; } @Override Public voidOnClick (View v) {//The context object is cast to the activity object. Activity C =(Activity) ConText; intcolor = 0 ; String Textcontext=NULL; Try {              //the bound text view that is madeThistext =(TextView) C.findviewbyid (R.ID.TEXTVIEW1); CM=(Connectivitymanager) C.getsystemservice (C.connectivity_service); Networkinfo Woin=Cm.getactivenetworkinfo (); if(woin!=NULL){                //There is a State table for the network to be set up with network statusTextcontext =c.getresources (). getString (R.STRING.NETWORK_OK); Color=c.getresources (). GetColor (R.color.green); }Else{                         //There is a State table for the network to be set up with network statusTextcontext =c.getresources (). getString (R.string.network_no); Color=c.getresources (). GetColor (r.color.red); }                       } Catch(Exception e) {Toast.maketext (c,"You don't have this permission.", Toast.length_long). Show (); }//Set text Thistext.settext (Textcontext) for this control;
Sets the background color thistext.setbackgroundcolor (color) for this control; }}

The core interpretation of whether there is a network code is

  CM =(connectivitymanager) c.getsystemservice (c.connectivity_service       == =null// there is no network, otherwise there is a connection network

Finally, pay special attention to:

When we go to get the status of the phone's connection network, we need to have a set of permissions, at this point we want to add a permission,

Otherwise, when the app runs, it will appear that the program has stopped and automatically exits the program.

(Note the above to get the phone network status code, I made a try....catch ....), carried out the capture, further to the warm hints. )

Where to add, what permissions to add, OK, let's look at it next.

Androidmanifest.xml in the bin directory of the project--res--

Double hit Open--again point permissions this interface type, add a permission


Select Users Permission Name: drop-down: Find Android.permission.ACCESS_NETWORK_STATE
(This is a permission to get the type of network connection)

3: Run the test results.

When there's a network.

When the mobile network is disconnected:

When the permissions are forgotten, the program I wrote above is processed.

I made a try...catch ... The handling of the exception was handled with warm and friendly hints (as we developers, the program may be the case, we all have to try.) Catch to be processed is the complete program.

Otherwise, to the user installation, to an exception, then the software is forced to quit, to the user experience is very bad)

--------------------------------------------------------------------------------------------------------------- ----------

--------------------------------------------------------------------------------------------------------------- -----------

The above is my judgment on the Android device Development network is connected to the code, feel your watch.

How to interpret whether the current device is connected to the network in Android development

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.