Android checks for Internet access

Source: Internet
Author: User

Article 1:

First, add the access permission in androidmanifest. xml:

<Uses-Permission Android: Name = "android. Permission. access_network_state"/>
Then add a function in *. java. If the connection cannot be accessed, exit and set the function as follows:
// Check the current network connection
Public void checkinternet ()
{
Connectivitymanager CM = (connectivitymanager) This. getsystemservice (context. connectivity_service );
Networkinfo info = cm. getactivenetworkinfo ();
If (info! = NULL & info. isconnected ())
{
// Connect to the Internet
Return;
}
Else
{
// Cannot be connected
Displaytoast ("You get not connect to the Internet, please log! ");
Try {
This. Wait (3000 );
} Catch (interruptedexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
This. Finish ();
}
}
For Android permission, visit the following link:

Http://developer.android.com/reference/android/Manifest.permission.html

Article 2: Android checks whether the Network is available and Internet requests

There are several ways to connect to the Internet for Android mobile phones.

WiFi

Cmnet

Cmwap

Wi-Fi and cmnet can be used when connected. cmwap accesses the Internet through mobile proxy and provides proxy services. However, the proxy IP addresses of China Mobile Unicom and China Telecom are different.

First, check whether the Network is available and the network type:

Public static Boolean isnetworkavailable (context CTX ){
Boolean isconnection = false;
Try {
Connectivitymanager CM = (connectivitymanager) CTX
. Getsystemservice (context. connectivity_service );
Networkinfo info = cm. getactivenetworkinfo ();
If (info! = NULL ){
String typename = info. gettypename (). tolowercase (); // WiFi/mobile
If (! Typename. Equals ("WiFi ")){
If (null! = Info. getextrainfo ()){
String WAP = info. getextrainfo (). tolowercase ();
// 3 GNET/3 gwap/uninet/uniwap/cmnet/cmwap/ctnet/ctwap
If (WAP. endswith ("WAP "))
Iswap = true;
}
}
Proxy = getproxy (CTX );
If (proxy! = NULL &&! Typename. Equals ("WiFi "))
Iswap = true;
Isconnection = info. isavailable ();
}
} Catch (exception e ){
E. printstacktrace ();
}
Return isconnection;
}

Set httpurlconnection connection Parameters

Private Static httpurlconnection connectionnetwap (string nameurl, string endurl) throws ioexception {
Httpurlconnection connection = NULL;
If (iswap ){
URL url = new URL ("http: //" + proxy + ": 80/" + endurl); // mobile Gateway
Connection = (httpurlconnection) URL. openconnection ();
Connection. setrequestproperty ("X-Online-host", nameurl );
Connection. setrequestproperty ("accept ","*/*");
} Else {
URL url = new URL (nameurl + endurl );
Connection = (httpurlconnection) URL. openconnection ();
}
Return connection;
}

Use

Public static string sendpostrequest (hashmap <string, Object> Params, string strurl)
{
String result = NULL;
Bufferedreader BR = NULL;
Httpurlconnection connection = NULL;
Dataoutputstream out = NULL;
Inputstream instream = NULL;
Try
{
// Parameters
Stringbuilder paraurl = new stringbuilder ();
Int Index = 0;
If (Params! = NULL &&! Params. isempty ()){
For (iterator it = Params. entryset (). iterator (); it. hasnext ();){
Map. Entry E = (Map. Entry) it. Next ();
If (index> 0)
Paraurl. append ("&");
Paraurl. append (E. getkey (). tostring ());
Paraurl. append ("= ");
Paraurl. append (urlencoder. encode (E. getvalue (). tostring (), "UTF-8 "));
Index ++;
}
}

// Non-wap mode:
// URL url = new URL (strurl );
// Connection = (httpurlconnection) URL. openconnection ();
// Adapt to all methods
Connection = connectionnetwap (serviceurl, strurl); // support WAP and net

// Set whether to output data to connection. Because this is a POST request, the parameter must be placed in the HTTP body, so it must be set to true.
Connection. setdooutput (true );
// Read from the connection. Default is true.
Connection. setdoinput (true );
// Set the POST method. Default is get
Connection. setrequestmethod ("Post ");
// The POST request cannot use the cache.
Connection. setusecaches (false );
// Urlconnection. setinstancefollowredirects is a member function that only acts on the current function.
Connection. setinstancefollowredirects (true );
// Configure the Content-Type of the connection and set it to application/X-WWW-form-urlencoded
// The body is the form parameter encoded by urlencoded. We can see that we use urlencoder. encode to encode the body content.
Connection. setrequestproperty ("Content-Type ",
"Application/X-WWW-form-urlencoded ");
// Connection. The configuration from posturl. openconnection () to this point must be completed before connect,
// Note that connection. getoutputstream implicitly performs connect.
Connection. Connect ();
Out = new dataoutputstream (connection
. Getoutputstream ());
// Body, the body content is actually in the get URL '? 'And the parameter strings are consistent
Out. writebytes (paraurl. tostring ());
Out. Flush ();
Stringbuilder sbuilder = new stringbuilder ();
// Obtain the input stream and read it using Reader
If (connection. getresponsecode () = httpurlconnection. http_ OK ){
Instream = connection. getinputstream ();
Inputstreamreader ISR = new inputstreamreader (instream, "UTF-8 ");
Int ichar;

While (ichar = ISR. Read ())! = 0 ){
Sbuilder. append (char) ichar );
}

Result = sbuilder. tostring ();
// ISR. Close ();
}
}
Catch (exception E)
{
Log. D ("HTTP", E. getmessage ());
Logmgr. getlogger (httputil. Class). Warning (E. getmessage ());
} Finally {
If (null! = Connection)
Connection. Disconnect ();
Try {

If (null! = Out)
Out. Close (); // flush and close
} Catch (ioexception IOE ){
Log. D ("HTTP", IOE. getmessage ());
}
}
Return result;
}


Related Article

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.