Android Network programming practices (I): network status detection

Source: Internet
Author: User

I have been developing and modifying lib support libraries under the android multi-media framework for a long time, and finally come to an end, but according to the project requirements, you need to write a network-related service, which is implemented in Java. In fact, I am familiar with Java Development on the framework and its application layer. I have done this for a while, including customizing views, implementing special interface effects, and using multimedia players and music editors. The only pity is that, since entering the embedded field, there has never been any network-related programming. This time, we readily agree that we want to take the opportunity to fill a gap in my career, private to the public is advantageous. Start to enter the topic.

The purpose of network status detection is to check whether the current device is connected to the network, the type, availability, and other information. These are the prerequisites for normal network communication. Note that the sample program provided here is run on emulator by default, and OS is of Version 2.3.

First, we will introduce two core classes for network status detection.:

1 ),Connectivitymanager($ Source/frameworks/base/CORE/Java/Android/NET/connectivitymanager. java): provides the network connection status and notifies the application when the network connection changes (for example, the Wi-Fi connection changes to a Bluetooth connection). The main responsibilities include:

(1) monitoring network connections (wi-fi, GPRS, UMTS, BT, etc );

(2) Send the broadcast intent to the application when the network connection changes;

(3) When the network connection fails, try "failed transfer" to another available network.

(4) Provide APIs to allow applications to query the coarse-grained and fine-grained status of Available Networks

2 ),Networkinfo($ Source/frameworks/base/CORE/Java/Android/NET/networkinfo. java): describes the status of a given type of network interface. As of 2.3.4 (more than 3.0 of the source code is not open), network connections only support mobile and Wi-Fi. By the way, this class is a storage body for network status information. It implements some interfaces in parcelable class, and other interfaces are used to set and query the network status. It is worth noting that two concepts are mentioned in the networkinfo source code: coarse-grained state (coarse-grained state) and fine-grained state (fine-grained state), which are the same as 1) the fourth point corresponds to the responsibilities. By analyzing the source code, coarse-grained States include: ing (connected), connected (connected), suspended (suspended), disconnecting (disconnected), disconnected (disconnected ), unknown (unknown state ). The fine-grained state is not described too much here. According to the source code comment, the application basically uses the coarse-grained state and rarely uses the fine-grained state. Of course, we can see from the source code analysis that the actual network connection is migrated by fine-grained state, but android has mapped fine-grained state to coarse-grained state, this is done through a State ing table. For example, if you set the fine-grained state (idle + scanning + connecting + authenticating + obtaining_ipaddr) all are mapped to disconnected of the coarse-grained state.

Secondly, my sample program:

(1) Main. xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    >    <TextView  android:id="@+id/netinfo"    android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="network information"    /></LinearLayout>

(2) networkexplorer. Java file where the activity is located

package com.android.sample.NetworkExplorer;import android.app.Activity;import android.content.Context;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.os.Bundle;import android.widget.TextView;public class NetworkExplorer extends Activity {ConnectivityManager cgr;NetworkInfo netinfo;TextView netinfo_tv;    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                netinfo_tv = (TextView)findViewById(R.id.netinfo);        cgr = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);    }@Overrideprotected void onStart() {super.onStart();netinfo = cgr.getActiveNetworkInfo();netinfo_tv.setText(netinfo.toString());}}

Finally, my journey to catch insects

Start emulator and execute the above Code. The result screen displays a large sorry. Check whether logcat provides the following error message:

ERROR/AndroidRuntime(1985): FATAL EXCEPTION: mainERROR/AndroidRuntime(1985): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.sample.                            NetworkExplorer/com.android.sample.NetworkExplorer.NetworkExplorer}: java.lang.SecurityException:                             ConnectivityService: Neither user 10042 nor current process has                             android.permission.ACCESS_NETWORK_STATE.ERROR/AndroidRuntime(1985):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1622)ERROR/AndroidRuntime(1985):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)ERROR/AndroidRuntime(1985):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)ERROR/AndroidRuntime(1985):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)ERROR/AndroidRuntime(1985):     at android.os.Handler.dispatchMessage(Handler.java:99)ERROR/AndroidRuntime(1985):     at android.os.Looper.loop(Looper.java:123)ERROR/AndroidRuntime(1985):     at android.app.ActivityThread.main(ActivityThread.java:3647)ERROR/AndroidRuntime(1985):     at java.lang.reflect.Method.invokeNative(Native Method)ERROR/AndroidRuntime(1985):     at java.lang.reflect.Method.invoke(Method.java:507)ERROR/AndroidRuntime(1985):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)ERROR/AndroidRuntime(1985):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)ERROR/AndroidRuntime(1985):     at dalvik.system.NativeStart.main(Native Method)ERROR/AndroidRuntime(1985): Caused by: java.lang.SecurityException: ConnectivityService:                             Neither user 10042 nor current process has android.permission.ACCESS_NETWORK_STATE.ERROR/AndroidRuntime(1985):     at android.os.Parcel.readException(Parcel.java:1322)ERROR/AndroidRuntime(1985):     at android.os.Parcel.readException(Parcel.java:1276)ERROR/AndroidRuntime(1985):     at android.net.IConnectivityManager$Stub$Proxy.getActiveNetworkInfo(IConnectivityManager.                                java:345)ERROR/AndroidRuntime(1985):     at android.net.ConnectivityManager.getActiveNetworkInfo(ConnectivityManager.java:242)ERROR/AndroidRuntime(1985):     at com.android.sample.NetworkExplorer.NetworkExplorer.onStart(NetworkExplorer.java:29)ERROR/AndroidRuntime(1985):     at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1129)ERROR/AndroidRuntime(1985):     at android.app.Activity.performStart(Activity.java:3791)ERROR/AndroidRuntime(1985):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1595)ERROR/AndroidRuntime(1985):     ... 11 more

Analyze the above error message from the bottom up. We can see that the onstart () function of networkexplorer activity executes networkexplorer. the crash triggered when the 29 lines of Java code are compared with the source code. The 29 lines are exactly the getactivenetworkinfo () of connectivitymanager, which is exactly the same as the next prompt of the error message. Following the same idea, I finally found that the application lacks the network access permission: Android. Permission. access_network_state. Therefore, in androidmanifest. XML, add the network access permission for the sample program, as follows:

...... (Omitted) <application Android: icon = "@ drawable/icon "...... (Omitted) </Application> <uses-Permission Android: Name = "android. permission. access_network_state "/>

Run the program again. The following information is output:

The Network Connection of emulator is analyzed as follows:

1) network connection type (type): The Master type is mobile, and the child type is utms (university mobile telecommunications system, 3G );

2) connection status (state): connected/connected (connected );

3) reason for using this connection (reason): simloaded (SIM card loaded). Currently, I have not paid attention to the network connection selection principles on Android, such: which connection method is selected when mobile and Wi-Fi are available;

4) Additional information (extra): Internet (IP network can be used );

5) roaming: false, not explained

6) failed transfer (Failover): false, see the third point in the previous connectivitymanager responsibility description

7), whether it is available (isavailable): True, not explained

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.