Home>

Demand details:

1), positioning operation is performed every 1 second in the service (gps + base station)

2) The positioning results are displayed on the interface in real time (requires longitude and latitude)

Technical Support:

1) Get the latitude and longitude

Get the latitude and longitude through gps + base station,First use gps to obtain, if it is empty to use a base station to obtain –>gps + base station (base station acquisition supports Unicom, telecommunications, mobile).

2) Get the latitude and longitude in real time

To achieve real-time latitude and longitude,You need to start the service of obtaining latitude and longitude in the background, and then send the latitude and longitude data through broadcast.Register broadcasts where you need them (such as registering broadcasts in your activity,(Shown in the interface)->Knowledge points such as service + broadcastreceiver + activity + thread are involved.

Remarks:This article focuses on practice.If you do n’t understand,First to consolidate the knowledge points,You can check out the related articles.

1. cellinfo entity class->Base Station Information

package com.ljq.activity;
/**
 * Base station information
 *
 * @author jiqinlin
 *
 * /
public class cellinfo {
 /** base station id, used to find the location of the base station * /
 private int cellid;
 /** mobile country code,3 in total, China is 460, which is the top 3 in imsi * /
 private string mobilecountrycode="460";
 /** mobile network code,There are 2 digits. In China, the code of mobile is 00 and 02, the code of China Unicom is 01, and the code of China Telecom is 03.
 private string mobilenetworkcode="0";
 /** area code * /
 private int locationareacode;
 /** signal type [select gsm | cdma | wcdma] * /
 private string radiotype="";
 public cellinfo () {
 }
 public int getcellid () {
 return cellid;
 }
 public void setcellid (int cellid) {
 this.cellid=cellid;
 }
 public string getmobilecountrycode () {
 return mobilecountrycode;
 }
 public void setmobilecountrycode (string mobilecountrycode) {
 this.mobilecountrycode=mobilecountrycode;
 }
 public string getmobilenetworkcode () {
 return mobilenetworkcode;
 }
 public void setmobilenetworkcode (string mobilenetworkcode) {
 this.mobilenetworkcode=mobilenetworkcode;
 }
 public int getlocationareacode () {
 return locationareacode;
 }
 public void setlocationareacode (int locationareacode) {
 this.locationareacode=locationareacode;
 }
 public string getradiotype () {
 return radiotype;
 }
 public void setradiotype (string radiotype) {
 this.radiotype=radiotype;
 }
}

2, gps class->gps package class, used to obtain latitude and longitude

package com.ljq.activity;
import android.content.context;
import android.location.criteria;
import android.location.location;
import android.location.locationlistener;
import android.location.locationmanager;
import android.os.bundle;
public class gps {
 private location location=null;
 private locationmanager locationmanager=null;
 private context context=null;
 /**
 * Initialize
 *
 * @param ctx
 * /
 public gps (context ctx) {
 context=ctx;
 locationmanager=(locationmanager) context.getsystemservice (context.location_service);
 location=locationmanager.getlastknownlocation (getprovider ());
 locationmanager.requestlocationupdates (locationmanager.gps_provider, 2000, 10, locationlistener);
 }
 //get location provider
 private string getprovider () {
 //Build location query criteria
 criteria criteria=new criteria ();
 //query accuracy:high
 criteria.setaccuracy (criteria.accuracy_fine);
 //Whether to check the sea dial:No
 criteria.setaltituderequired (false);
 //Whether to query the azimuth:No
 criteria.setbearingrequired (false);
 //Whether to allow payment:Yes
 criteria.setcostallowed (true);
 //Battery requirement:low
 criteria.setpowerrequirement (criteria.power_low);
 //Returns the most suitable qualified provider. The second parameter is true, if only one provider is valid,Return the current provider
 return locationmanager.getbestprovider (criteria, true);
 }
 private locationlistener locationlistener=new locationlistener () {
 //called after the position has changed
 public void onlocationchanged (location l) {
  if (l!=null) {
  location=l;
  }
 }
 //called after the provider is closed by the user
 public void onproviderdisabled (string provider) {
  location=null;
 }
 //called after the provider is started by the user
 public void onproviderenabled (string provider) {
  location l=locationmanager.getlastknownlocation (provider);
  if (l!=null) {
  location=l;
  }
 }
 //called when the provider state changes
 public void onstatuschanged (string provider, int status, bundle extras) {
 }
 };
 public location getlocation () {
 return location;
 }
 public void closelocation () {
 if (locationmanager!=null) {
  if (locationlistener!=null) {
  locationmanager.removeupdates (locationlistener);
  locationlistener=null;
  }
  locationmanager=null;
 }
 }
}

3.gpsservice service class

package com.ljq.activity;
import java.util.arraylist;
import android.app.service;
import android.content.intent;
import android.location.location;
import android.os.ibinder;
import android.util.log;
public class gpsservice extends service {
 arraylist<cellinfo>cellids=null;
 private gps gps=null;
 private boolean threaddisable=false;
 private final static string tag=gpsservice.class.getsimplename ();
 @override
 public void oncreate () {
 super.oncreate ();
 gps=new gps (gpsservice.this);
 cellids=utiltool.init (gpsservice.this);
 new thread (new runnable () {
  @override
  public void run () {
  while (! threaddisable) {
   try {
   thread.sleep (1000);
   } catch (interruptedexception e) {
   e.printstacktrace ();
   }
   if (gps!=null) {//gps is empty when the service ends
   //Get the latitude and longitude
   location location=gps.getlocation ();
   //If gps cannot get latitude and longitude,Use base station positioning instead
   if (location == null) {
    log.v (tag, "gps location null");
    //2. Get latitude and longitude based on base station information
    try {
    location=utiltool.callgear (gpsservice.this, cellids);
    } catch (exception e) {
    location=null;
    e.printstacktrace ();
    }
    if (location == null) {
    log.v (tag, "cell location null");
    }
   }
   //Send broadcast
   intent intent=new intent ();
   intent.putextra ("lat", location == null?"":location.getlatitude () + "");
   intent.putextra ("lon", location == null?"":location.getlongitude () + "");
   intent.setaction ("com.ljq.activity.gpsservice");
   sendbroadcast (intent);
   }
  }
  }
 }). start ();
 }
 @override
 public void ondestroy () {
 threaddisable=true;
 if (cellids!=null&&cellids.size ()>0) {
  cellids=null;
 }
 if (gps!=null) {
  gps.closelocation ();
  gps=null;
 }
 super.ondestroy ();
 }
 @override
 public ibinder onbind (intent arg0) {
 return null;
 }
}

4, gpsactivity->real-time display of latitude and longitude data on the interface

package com.ljq.activity;
import android.app.activity;
import android.content.broadcastreceiver;
import android.content.context;
import android.content.intent;
import android.content.intentfilter;
import android.location.location;
import android.location.locationmanager;
import android.os.bundle;
import android.util.log;
import android.widget.edittext;
import android.widget.toast;
public class gpsactivity extends activity {
 private double homelat=26.0673834d;//dormitory latitude
 private double homelon=119.3119936d;//Longitude of dormitory
 private edittext edittext=null;
 private myreceiver receiver=null;
 private final static string tag=gpsactivity.class.getsimplename ();
 @override
 public void oncreate (bundle savedinstancestate) {
 super.oncreate (savedinstancestate);
 setcontentview (r.layout.main);
 edittext=(edittext) findviewbyid (r.id.edittext);
 //Judge whether GPS is available
 log.i (tag, utiltool.isgpsenabled ((locationmanager) getsystemservice (context.location_service)) + "");
 if (! utiltool.isgpsenabled ((locationmanager) getsystemservice (context.location_service))) {
  toast.maketext (this, "gsp is currently disabled,Please launch at your system settings screen.
", toast.length_long) .show ();
  intent callgpssettingintent=new intent (android.provider.settings.action_location_source_settings);
  startactivity (callgpssettingintent);
      return;
 }
 //start the service
 startservice (new intent (this, gpsservice.class));
 //Register broadcast
 receiver=new myreceiver ();
 intentfilter filter=new intentfilter ();
 filter.addaction ("com.ljq.activity.gpsservice");
 registerreceiver (receiver, filter);
 }
 //Get broadcast data
 private class myreceiver extends broadcastreceiver {
 @override
 public void onreceive (context context, intent intent) {
  bundle bundle=intent.getextras ();
  string lon=bundle.getstring ("lon");
  string lat=bundle.getstring ("lat");
  if (lon!=null&&! "". equals (lon)&&lat!=null &&! "". equals (lat)) {
  double distance=getdistance (double.parsedouble (lat),   double.parsedouble (lon), homelat, homelon);
  edittext.settext ("Current latitude and longitude \ nLongitude:" + lon + "\ nLatitude:" + lat + "\ nDistance from dormitory:" + java.lang.math.abs (distance));
  } else {
  edittext.settext ("Current latitude and longitude \ nLongitude:" + lon + "\ nLatitude:" + lat);
  }
 }
 }
 @override
 protected void ondestroy () {
 //Cancel service
 unregisterreceiver (receiver);
 //End the service,If i want the service to keep running, log out of this sentence
 stopservice (new intent (this, gpsservice.class));
 super.ondestroy ();
 }
 /**
 * Convert latitude and longitude to distance
 *
 * @param lat1 start latitude
 * @param lon1 start longitude
 * @param lat2 end latitude
 * @param lon2 end longitude
 * @return
 * /
 private double getdistance (double lat1, double lon1, double lat2, double lon2) {
 float [] results=new float [1];
 location.distancebetween (lat1, lon1, lat2, lon2, results);
 return results [0];
 }
}

5, utiltool->tools

package com.ljq.activity;
import java.io.bytearrayoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import java.io.unsupportedencodingexception;
import java.net.httpurlconnection;
import java.net.malformedurlexception;
import java.net.protocolexception;
import java.net.url;
import java.util.arraylist;
import java.util.calendar;
import java.util.list;
import java.util.locale;
import org.apache.http.client.clientprotocolexception;
import org.json.jsonexception;
import org.json.jsonobject;
import android.content.context;
import android.location.location;
import android.location.locationmanager;
import android.telephony.neighboringcellinfo;
import android.telephony.telephonymanager;
import android.telephony.cdma.cdmacelllocation;
import android.telephony.gsm.gsmcelllocation;
import android.util.log;
import android.widget.toast;
public class utiltool {
 public static boolean isgpsenabled (locationmanager locationmanager) {
 boolean isopengps=locationmanager.isproviderenabled (android.location.locationmanager.gps_provider);
 boolean isopennetwork=locationmanager.isproviderenabled (android.location.locationmanager.network_provider);
 if (isopengps || isopennetwork) {
  return true;
 }
 return false;
 }
  /**
   * Get latitude and longitude based on base station information
   *
   * Principle Send http post request to http://www.google.com/loc/json, get latitude and longitude according to the result returned by google
   *
   * @param cellids
   * @return
   * @throws exception
   * /
  public static location callgear (context ctx, arraylist<cellinfo>cellids) throws exception {
   string result="";
   jsonobject data=null;
   if (cellids == null || cellids.size () == 0) {
   utiltool.alert (ctx, "cell request param null");
   return null;
   };
 try {
  result=utiltool.getresponseresult (ctx, "http://www.google.com/loc/json", cellids);
  if (result.length ()<= 1)
  return null;
  data=new jsonobject (result);
  data=(jsonobject) data.get ("location");
  location loc=new location (locationmanager.network_provider);
  loc.setlatitude ((double) data.get ("latitude"));
  loc.setlongitude ((double) data.get ("longitude"));
  loc.setaccuracy (float.parsefloat (data.get ("accuracy"). tostring ()));
  loc.settime (utiltool.getutctime ());
  return loc;
 } catch (jsonexception e) {
  return null;
 } catch (unsupportedencodingexception e) {
  e.printstacktrace ();
 } catch (clientprotocolexception e) {
  e.printstacktrace ();
 } catch (ioexception e) {
  e.printstacktrace ();
 }
 return null;
 }
  /**
   * Receive data format returned by Google
   *
 * Input:{"location":{"latitude":26.0673834, "longitude":119.3119936, * "address":{"country":"ä¸å›"&Ordm;ç"
 * "street":"五ä&cede;€accuracy ":935.0}, * "access_token":"2:xiu8yrsiffhuavrj:aj9k70vjmrwo_9_g"}
 * Request path:http://maps.google.cn/maps/geo?key=abcdefg&q=26.0673834,119.3119936
   *
   * @param cellids
   * @return
   * @throws unsupportedencodingexception
   * @throws malformedurlexception
   * @throws ioexception
   * @throws protocolexception
   * @throws exception
   * /
 public static string getresponseresult (context ctx, string path, arraylist<cellinfo>cellinfos)
  throws unsupportedencodingexception, malformedurlexception,  ioexception, protocolexception, exception {
 string result="";
 log.i (ctx.getapplicationcontext (). getclass (). getsimplename (),  "in param:" + getrequestparams (cellinfos));
 inputstream instream=utiltool.sendpostrequest (path,  getrequestparams (cellinfos), "utf-8");
 if (instream!=null) {
  byte [] datas=utiltool.readinputstream (instream);
  if (datas!=null&&datas.length>0) {
  result=new string (datas, "utf-8");
  //log.i(ctx.getclass (). getsimplename (), "receive result:" + result);//Result information returned by the server
  log.i (ctx.getapplicationcontext (). getclass (). getsimplename (),    "google cell receive data result:" + result);
  } else {
  log.i (ctx.getapplicationcontext (). getclass (). getsimplename (),   "google cell receive data null");
  }
 } else {
  log.i (ctx.getapplicationcontext (). getclass (). getsimplename (),    "google cell receive instream null");
 }
 return result;
 }
 /**
 * Assemble json request parameters,Assembling base station information
 *
 * Input:{"version":"1.1.0", "host":"maps.google.com", "home_mobile_country_code":460, * "home_mobile_network_code":14136, "radio_type":"cdma", "request_address":true, * "address_language":"zh_cn", "cell_towers":[{"cell_id":"12835", "location_area_code":6, * "mobile_country_code":460, "mobile_network_code":14136, "age":0}]}
 * @param cellinfos
 * @return
 * /
 public static string getrequestparams (list<cellinfo>cellinfos) {
 stringbuffer sb=new stringbuffer ("");
 sb.append ("{");
 if (cellinfos!=null&&cellinfos.size ()>0) {
  sb.append ("" version ":" 1.1.0 ",");//google api version [required]
  sb.append ("" host ":" maps.google.com ",");//server domain name [required]
  sb.append ("" home_mobile_country_code ":" + cellinfos.get (0) .getmobilecountrycode () + ",");//The country code of the mobile user [Select China460]
  sb.append ("" home_mobile_network_code ":" + cellinfos.get (0) .getmobilenetworkcode () + ",");//mobile system number [default 0]
  sb.append ("" radio_type ":" "+ cellinfos.get (0) .getradiotype () +" ",");//Signal type [select gsm | cdma | wcdma]
  sb.append ("" request_address ":true,");//Whether to return data [Required]
  sb.append ("" address_language ":" zh_cn ",");//Feedback data language [choose China zh_cn]
  sb.append ("" cell_towers ":[");//Mobile base station parameter object [Required]
  for (cellinfo cellinfo:cellinfos) {
  sb.append ("{");
  sb.append ("" cell_id ":" "+ cellinfo.getcellid () +" ",");//base station id [Required]
  sb.append ("" location_area_code ":" + cellinfo.getlocationareacode () + ",");//Area code [Required]
  sb.append ("" mobile_country_code ":" + cellinfo.getmobilecountrycode () + ",");
  sb.append ("" mobile_network_code ":" + cellinfo.getmobilenetworkcode () + ",");
  sb.append ("" age ":0");//A database that has been used for a long time [select the default 0 to use the latest database]
  sb.append ("},");
  }
  sb.deletecharat (sb.length ()-1);
  sb.append ("]");
 }
 sb.append ("}");
 return sb.tostring ();
 }
 /**
 * Get UTC time
 *
 * utc+ time zone difference=local time (Beijing is Dongba District)
 *
 * @return
 * /
 public static long getutctime () {
   //Get local time
    calendar cal=calendar.getinstance (locale.china);
    //Get time offset
    int zoneoffset=cal.get (java.util.calendar.zone_offset);
    //Get daylight saving time
    int dstoffset=cal.get (java.util.calendar.dst_offset);
    //Deduct these differences from local time,That can get utc time
    cal.add (java.util.calendar.millisecond,-(zoneoffset + dstoffset));
    return cal.gettimeinmillis ();
  }
 /**
 * Initialization, remember to initialize in the oncreate () method,Get base station information
 *
 * @return
 * /
 public static arraylist<cellinfo>init (context ctx) {
 arraylist<cellinfo>cellinfos=new arraylist<cellinfo>();
 telephonymanager tm=(telephonymanager) ctx.getsystemservice (context.telephony_service);
 //Network system
 int type=tm.getnetworktype ();
   /**
   * Get sim card's imsi code
   * sim card unique identification:imsi international mobile subscriber identification number (imsi:international mobile subscriber identification number) is a sign that distinguishes mobile users,   * Stored in the sim card, can be used to distinguish valid information from mobile users.
imsi consists of mcc, mnc, msin, where mcc is the mobile country number,Consists of 3 digits,   * Uniquely identify the country the mobile customer belongs to,China is 460;mnc is the network id, which consists of 2 digits.
   * Used to identify the mobile network to which the mobile customer belongs,00 for China Mobile, 01 for China Unicom, and 03 for China Telecom;msin is the mobile customer identification code.
It consists of 11 digits of equal length.
   * Uniquely identify mobile customers in domestic GSM mobile communication networks.
So we have to distinguish between mobile and China Unicom.
Just get the mnc field in the sim card
  * /
 string imsi=tm.getsubscriberid ();
 alert (ctx, "imsi:" + imsi);
 //In order to distinguish between mobile, China Unicom and telecommunications,It is recommended to use imsi to judge (unless you use getnetworktype (), such as when imsi is empty)
 if (imsi!=null &&! "". equals (imsi)) {
  alert (ctx, "imsi");
  if (imsi.startswith ("46000") || imsi.startswith ("46002")) {//Because imsi under mobile network number 46000 has run out
Therefore, a 46002 number is virtualized, and this number is used in paragraph 134/159.
  //China Mobile
  mobile (cellinfos, tm);
  } else if (imsi.startswith ("46001")) {
  //China Unicom
  union (cellinfos, tm);
  } else if (imsi.startswith ("46003")) {
  //China Telecom
  cdma (cellinfos, tm);
  }
 } else {
  alert (ctx, "type");
  //In China, 3g for China Unicom is umts or hsdpa, and 3g for Telecom is evdo
  //In China, 2g for mobile is egde, 2g for China Unicom is gprs, 2g for Telecom is cdma
  //string operatorname=tm.getnetworkoperatorname ();
  //China Telecom
  if (type == telephonymanager.network_type_evdo_a
   || type == telephonymanager.network_type_evdo_0
   || type == telephonymanager.network_type_cdma
   || type == telephonymanager.network_type_1xrtt) {
  cdma (cellinfos, tm);
  }
  //mobile (edge ​​(2.75g) is an upgraded version of gprs (2.5g),Faster than gprs. At present, mobile is basically upgrading and popularizing edge in China, and China Unicom is deploying edge in big cities. )
  else if (type == telephonymanager.network_type_edge
   || type == telephonymanager.network_type_gprs) {
  mobile (cellinfos, tm);
  }
  //Unicom (edge ​​(2.75g) is an upgraded version of gprs (2.5g),Faster than gprs. At present, mobile is basically upgrading and popularizing edge in China, and China Unicom is deploying edge in big cities. )
  else if (type == telephonymanager.network_type_gprs
   || type == telephonymanager.network_type_edge
   || type == telephonymanager.network_type_umts
   || type == telephonymanager.network_type_hsdpa) {
  union (cellinfos, tm);
  }
 }
 return cellinfos;
 }
 /**
 * Telecommunications
 *
 * @param cellinfos
 * @param tm
 * /
 private static void cdma (arraylist<cellinfo>cellinfos, telephonymanager tm) {
 cdmacelllocation location=(cdmacelllocation) tm.getcelllocation ();
 cellinfo info=new cellinfo ();
 info.setcellid (location.getbasestationid ());
 info.setlocationareacode (location.getnetworkid ());
 info.setmobilenetworkcode (string.valueof (location.getsystemid ()));
 info.setmobilecountrycode (tm.getnetworkoperator (). substring (0, 3));
 info.setradiotype ("cdma");
 cellinfos.add (info);
 //All the information obtained before is a single base station,Next, acquire the information of nearby neighboring base stations to assist the accuracy of positioning through the base station
 //Get information about nearby base stations
 list<neighboringcellinfo>list=tm.getneighboringcellinfo ();
 int size=list.size ();
 for (int i=0;i<size;i ++) {
  cellinfo cell=new cellinfo ();
  cell.setcellid (list.get (i) .getcid ());
  cell.setlocationareacode (location.getnetworkid ());
  cell.setmobilenetworkcode (string.valueof (location.getsystemid ()));
  cell.setmobilecountrycode (tm.getnetworkoperator (). substring (0, 3));
  cell.setradiotype ("cdma");
  cellinfos.add (cell);
 }
 }
 /**
 * Mobile
 *
 * @param cellinfos
 * @param tm
 * /
 private static void mobile (arraylist<cellinfo>cellinfos,  telephonymanager tm) {
 gsmcelllocation location=(gsmcelllocation) tm.getcelllocation ();
 cellinfo info=new cellinfo ();
 info.setcellid (location.getcid ());
 info.setlocationareacode (location.getlac ());
 info.setmobilenetworkcode (tm.getnetworkoperator (). substring (3, 5));
 info.setmobilecountrycode (tm.getnetworkoperator (). substring (0, 3));
 info.setradiotype ("gsm");
 cellinfos.add (info);
 //All the information obtained before is a single base station,Next, acquire the information of nearby neighboring base stations to assist the accuracy of positioning through the base station
 //Get information about nearby base stations
 list<neighboringcellinfo>list=tm.getneighboringcellinfo ();
 int size=list.size ();
 for (int i=0;i<size;i ++) {
  cellinfo cell=new cellinfo ();
  cell.setcellid (list.get (i) .getcid ());
  cell.setlocationareacode (location.getlac ());
  cell.setmobilenetworkcode (tm.getnetworkoperator (). substring (3, 5));
  cell.setmobilecountrycode (tm.getnetworkoperator (). substring (0, 3));
  cell.setradiotype ("gsm");
  cellinfos.add (cell);
 }
 }
 /**
 * Unicom
 *
 * @param cellinfos
 * @param tm
 * /
 private static void union (arraylist<cellinfo>cellinfos, telephonymanager tm) {
 gsmcelllocation location=(gsmcelllocation) tm.getcelllocation ();
 cellinfo info=new cellinfo ();
 //after testing,The following two lines of obtaining Unicom data must be removed,Otherwise an error will occur,The error type is json parsing error
 //info.setmobilenetworkcode(tm.getnetworkoperator().substring(3, 5));
 //info.setmobilecountrycode(tm.getnetworkoperator().substring(0, 3));
 info.setcellid (location.getcid ());
 info.setlocationareacode (location.getlac ());
 info.setmobilenetworkcode ("");
 info.setmobilecountrycode ("");
 info.setradiotype ("gsm");
 cellinfos.add (info);
 //All the information obtained before is a single base station,Next, acquire the information of nearby neighboring base stations to assist the accuracy of positioning through the base station
 //Get information about nearby base stations
 list<neighboringcellinfo>list=tm.getneighboringcellinfo ();
 int size=list.size ();
 for (int i=0;i<size;i ++) {
  cellinfo cell=new cellinfo ();
  cell.setcellid (list.get (i) .getcid ());
  cell.setlocationareacode (location.getlac ());
  cell.setmobilenetworkcode ("");
  cell.setmobilecountrycode ("");
  cell.setradiotype ("gsm");
  cellinfos.add (cell);
 }
 }
 /**
 * Tip
 *
 * @param ctx
 * @param msg
 * /
 public static void alert (context ctx, string msg) {
 toast.maketext (ctx, msg, toast.length_long) .show ();
 }
 /**
 * Send a post request and return the input stream
 *
 * @param path access path
 * @param params json data format
 * @param encoding
 * @return
 * @throws unsupportedencodingexception
 * @throws malformedurlexception
 * @throws ioexception
 * @throws protocolexception
 * /
 public static inputstream sendpostrequest (string path, string params, string encoding)
 throws unsupportedencodingexception, malformedurlexception, ioexception, protocolexception {
 byte [] data=params.getbytes (encoding);
 url url=new url (path);
 httpurlconnection conn=(httpurlconnection) url.openconnection ();
 conn.setrequestmethod ("post");
 conn.setdooutput (true);
 //application/x-javascript text/xml->xml data application/x-javascript->json object application/x-www-form-urlencoded->form data
 conn.setrequestproperty ("content-type", "application/x-javascript;charset =" + encoding);
 conn.setrequestproperty ("content-length", string.valueof (data.length));
 conn.setconnecttimeout (5 * 1000);
 outputstream outstream=conn.getoutputstream ();
 outstream.write (data);
 outstream.flush ();
 outstream.close ();
 if (conn.getresponsecode () == 200)
  return conn.getinputstream ();
 return null;
 }
 /**
 * Send a get request
 *
 * @param path request path
 * @return
 * @throws exception
 * /
 public static string sendgetrequest (string path) throws exception {
 url url=new url (path);
 httpurlconnection conn=(httpurlconnection) url.openconnection ();
 conn.setconnecttimeout (5 * 1000);
 conn.setrequestmethod ("get");
 inputstream instream=conn.getinputstream ();
 byte [] data=readinputstream (instream);
 string result=new string (data, "utf-8");
 return result;
 }
 /**
 * Read data from the input stream
 * @param instream
 * @return
 * @throws exception
 * /
 public static byte [] readinputstream (inputstream instream) throws exception {
 bytearrayoutputstream outstream=new bytearrayoutputstream ();
 byte [] buffer=new byte [1024];
 int len ​​= 0;
 while ((len=instream.read (buffer))! =-1) {
  outstream.write (buffer, 0, len);
 }
 byte [] data=outstream.tobytearray ();//The binary data of the web page
 outstream.close ();
 instream.close ();
 return data;
 }
}

6, main.xml->layout file

<?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">
  <edittext android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:cursorvisible="false"
    android:editable="false"
    android:id="@ + id/edittext" />
</linearlayout>

7. Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.ljq.activity" android:versioncode="1"
 android:versionname="1.0">
 <application android:icon="@ drawable/icon"
 android:label="@ string/app_name">
 <activity android:name=". Gpsactivity"
  android:label="@ string/app_name">
  <intent-filter>
  <action android:name="android.intent.action.main" />
  <category
   android:name="android.intent.category.launcher" />
  </intent-filter>
 </activity>
 <service android:label="gpsservice" android:name=". Gpsservice" />
 </application>
 <uses-sdk android:minsdkversion="7" />
 <uses-permission android:name="android.permission.access_fine_location" />
 <uses-permission android:name="android.permission.access_coarse_location" />
 <uses-permission android:name="android.permission.internet" />
 <uses-permission android:name="android.permission.read_phone_state" />
 <uses-permission android:name="android.permission.access_wifi_state" />
</manifest>

The effect is as follows:

  • Previous Java Swing radio box usage example analysis
  • Next Quickly add multi-user and database skills to mysql by reading and executing commands from documents