如何在android中获取地址

时间:2013-10-31 06:13:04

标签: android web-services geolocation

你好朋友,我是Android开发的新手。

我试图使用以下代码查找地址... 在模拟器中它没有在log cat中显示任何消息。但当我在我的设备上推出这个应用程序 它每次都停止...... 如果有人可以建议我如何从设备读取log cat massege以及如何使用此代码获取地址... 如果代码中有任何错误,请建议我如何修复它。

gps类的代码......

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;


    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude


    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
    public static final Double val =  10.0;




    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        //getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            //isGPSEnabled = locationManager
                    //.isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled || !isNetworkEnabled) {
                // no network provider is enabled
                //Toast.makeText(getApplicationContext(), "no gps or network found", Toast.LENGTH_SHORT).show();
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    if (location == null) {
                        Criteria criteria = new Criteria();
                        criteria.setAccuracy(Criteria.ACCURACY_FINE);  
                        // 高精度  
                        criteria.setAltitudeRequired(false);  
                        criteria.setBearingRequired(false);  
                        criteria.setCostAllowed(true);   
                        criteria.setPowerRequirement(Criteria.POWER_LOW);  
                        String provider = locationManager.getBestProvider(criteria, true);
                    locationManager.requestLocationUpdates(
                            provider,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                /*if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }*/
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }       
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }




    @Override
    public void onLocationChanged(Location location) {
        //makeUseOfNewLocation(location);
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    }

mainActivity的代码

public class Act1 extends Activity{
 TextView loc;
 GPSTracker gps;
 Location location;
 String mAddress="";
 Criteria criteria;
 String providername="";
 String device_id="";
 String ph="";
 double lat,lon;
 int lac=0,cid=0;
 String address2="";
 String MyAddress="";
 protected LocationManager locationManager;

 public void onCreate(Bundle b){
     super.onCreate(b);
    setContentView(R.layout.main);
    loc=(TextView)findViewById(R.id.loc);

    gps=new GPSTracker(getApplicationContext());
    location=gps.getLocation();



    if (gps.latitude != 0 || gps.longitude != 0){

        Act1.getFromLocation(gps.getLatitude(), gps.getLongitude(), 10);

    for(int i=0;i<Act1.getFromLocation(gps.getLatitude(), gps.getLongitude(), 10).size();i++){

          MyAddress+=Act1.getFromLocation(gps.getLatitude(), gps.getLongitude(), 10).get(i).toString();

        }
    }

    loc.setText(MyAddress);

 }
 public static List<Address> getFromLocation(double lat, double lng, int maxResult){

        String address = String.format(Locale.ENGLISH,"http://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=true&language="+Locale.getDefault().getCountry(), lat, lng);
        HttpGet httpGet = new HttpGet(address);
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        StringBuilder stringBuilder = new StringBuilder();

        List<Address> retList = null;

        try {
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            int b;
            while ((b = stream.read()) != -1) {
                stringBuilder.append((char) b);
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject = new JSONObject(stringBuilder.toString());


            retList = new ArrayList<Address>();


            if("OK".equalsIgnoreCase(jsonObject.getString("status"))){
                JSONArray results = jsonObject.getJSONArray("results");
                for (int i=0;i<results.length();i++ ) {
                    JSONObject result = results.getJSONObject(i);
                    String indiStr = result.getString("formatted_address");
                    Address addr = new Address(Locale.getDefault());
                    addr.setAddressLine(0, indiStr);
                    retList.add(addr);
                }
            }


        } catch (ClientProtocolException e) {
            Log.e(Act1.class.getName(), "Error calling Google geocode webservice.", e);
        } catch (IOException e) {
            Log.e(Act1.class.getName(), "Error calling Google geocode webservice.", e);
        } catch (JSONException e) {
            Log.e(Act1.class.getName(), "Error parsing Google geocode webservice response.", e);
        }

        return retList;
    }


}

3 个答案:

答案 0 :(得分:0)

添加logcat消息的说明,

打开logcat并单击添加新的logcat过滤器并将您的包名称粘贴到过滤器名称编辑文本和应用程序名称编辑文本中。然后单击确定。

您还需要在DDMS上选择设备。哪一个是你连接到系统。

答案 1 :(得分:0)

获取getFromLocation(lat,lag,maxvalue)maxvalue需要1到5,并且还提供权限gps提供程序。可能是它的工作。

答案 2 :(得分:0)

试试这段代码...... 我找到旅程的起始地址和旅程的结束地址。你需要什么来定制代码。

应用程序启动时启动服务,暂停活动时停止服务。

使用模拟器控件发送gps数据

// ----- GeocoderHelper.java ------------------

import java.util.List;
import java.util.Locale;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.location.Geocoder;
import android.location.Location;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;

public class GeocoderHelper
{
    private static final AndroidHttpClient ANDROID_HTTP_CLIENT = AndroidHttpClient.newInstance(GeocoderHelper.class.getName());

    private String address="";
    private Location i_Location;
    private Context i_Context;
    public String fetchCityName(final Context contex, final Location location)
    {
        i_Location = location;
        i_Context = contex;
      try {
            return new Address().execute().get();
        } catch (Exception e) {

            return address;

        } 
    }



    public class Address extends AsyncTask<Void, Void, String>
    {



        @SuppressWarnings("unused")
        @Override
        protected String doInBackground(Void... params)
        {
            String cityName = null;

            if (Geocoder.isPresent())
            {
                try
                {
                    System.out.println("location latitude is"+i_Location.getLatitude());
                    System.out.println("location longitude is"+i_Location.getLongitude());

                    Geocoder geocoder = new Geocoder(i_Context, Locale.getDefault());
                    List<android.location.Address> addresses = geocoder.getFromLocation(i_Location.getLatitude(), i_Location.getLongitude(), 1);
                    if (addresses.size() > 0)
                    {
                        //cityName = addresses.get(0).getLocality();
                        address = addresses.get(0).getLocality();
                        System.out.println("geocoder inside present address is"+address);

                    }
                }
                catch (Exception ignored)
                {
                    // after a while, Geocoder start to trhow "Service not availalbe" exception. really weird since it was working before (same device, same Android version etc..
                }
            }

            if (cityName != null) // i.e., Geocoder succeed
            {
                return cityName;
            }
            else // i.e., Geocoder failed
            {
                return fetchCityNameUsingGoogleMap();
            }

        }

        // Geocoder failed :-(
        // Our B Plan : Google Map
        private String fetchCityNameUsingGoogleMap()
        {


            try
            {
                String googleMapUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + i_Location.getLatitude() + ","
                        + i_Location.getLongitude() + "&sensor=false&language=fr";

                JSONObject googleMapResponse = new JSONObject(ANDROID_HTTP_CLIENT.execute(new HttpGet(googleMapUrl),
                        new BasicResponseHandler()));

                // many nested loops.. not great -> use expression instead
                // loop among all results
                JSONArray results = (JSONArray) googleMapResponse.get("results");
                for (int i = 0; i < results.length(); i++)
                {
                    // loop among all addresses within this result
                    JSONObject result = results.getJSONObject(i);
                    address = result.getString("formatted_address");
                    System.out.println("map address:"+address);
                    break;

          /*          if (result.has("address_components"))
                    {
                        JSONArray addressComponents = result.getJSONArray("address_components");
                        // loop among all address component to find a 'locality' or 'sublocality'
                        for (int j = 0; j < addressComponents.length(); j++)
                        {
                            JSONObject addressComponent = addressComponents.getJSONObject(j);
                            if (result.has("types"))
                            {
                                JSONArray types = addressComponent.getJSONArray("types");

                                // search for locality and sublocality
                                String cityName = null;
                                String ROUTE= null;

                                for (int k = 0; k < types.length(); k++)
                                {

                                    if ("locality".equals(types.getString(k)) && cityName == null)
                                    {
                                        if (addressComponent.has("long_name"))
                                        {
                                            cityName = addressComponent.getString("long_name");
                                        }
                                        else if (addressComponent.has("short_name"))
                                        {
                                            cityName = addressComponent.getString("short_name");
                                        }
                                    }
                                    if ("sublocality".equals(types.getString(k)))
                                    {
                                        if (addressComponent.has("long_name"))
                                        {
                                            cityName = addressComponent.getString("long_name");
                                        }
                                        else if (addressComponent.has("short_name"))
                                        {
                                            cityName = addressComponent.getString("short_name");
                                        }
                                    }
                                }
                                if (cityName != null)
                                {
                                    address = cityName;
                                    return cityName;

                                }
                            }
                        }
                    }*/
                }
            }
            catch (Exception ignored)
            {
                ignored.printStackTrace();
            }
            return address;
        }

        protected void onPostExecute(String result)
        {

              super.onPostExecute(result);
        }
    }
}

// ----------------- MWService.java ---------------

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Scanner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Settings;

public class MWService extends Service implements LocationListener {


    private LocationManager myLocationManager;
    private LocationProvider myLocationProvider;
    private NotificationManager myNotificationManager;
    private long frequency;
    private double total_distance = 0;
    private Location currentLocation;
    public static final String BROADCAST_ACTION = "com.motorvehicle.android";
    private final Handler handler = new Handler();
    Intent intent;
    private GeocoderHelper geocoder  = new GeocoderHelper();
    private boolean isStart=true;
    private Location startLocation,endLocation;
    private String startAddress="";
    private String endAddress="";
    private JSONArray jarray = new JSONArray();
    private boolean isInternet;

    public void onLocationChanged(Location newLocation) {
        try {
            System.out.println("latitude current :"+currentLocation.getLatitude());
            System.out.println("latitude current :"+currentLocation.getLongitude());
            System.out.println("latitude new  :"+newLocation.getLatitude());
            System.out.println("latitude new  :"+newLocation.getLongitude());
            System.out.println("distance total :"+total_distance);
            //System.out.println(distance(22.306813, 73.180239,22.301016, 73.177986, 'K') + " Kilometers\n");
            double diff = 0.0;
            diff = currentLocation.getLatitude()- newLocation.getLatitude();
            System.out.println("difference ::"+diff);
            if(diff != 0){
                total_distance = total_distance + currentLocation.distanceTo(newLocation);
            }


            if(isStart){
                isStart = false;
                startLocation = newLocation;
            /*  if(InternetAvailable()){
                    //startAddress =    geocoder.fetchCityName(getApplicationContext(),newLocation);
                    System.out.println("start address:"+startAddress);
                }*/

            }else{
                endLocation = newLocation;
                /*if(InternetAvailable()){
                    //endAddress =  geocoder.fetchCityName(getApplicationContext(),newLocation);
                    System.out.println("endAddress :"+endAddress);
                }*/
            }

            currentLocation = newLocation;
        } catch (Exception e) {
            currentLocation = newLocation;
            e.printStackTrace();
        }
    }

    public boolean InternetAvailable() {

        Thread t = new Thread(new Runnable() {


            @Override
            public void run() {
                // while(isStopMe){
                System.out.println("This is inside ................. :");
                try {
                    if (!checkConnection()) {
                        System.out.println("No Internet Connectivity");
                        isInternet = false;
                        System.out.println("First");
                    } else {
                        if (inetAddr()) {
                            System.out.println("Net Connectivity is Present");
                            isInternet = true;
                            System.out.println("Second");
                        } else {
                            if (mobileConnect()) {
                                System.out.println("THIRD");
                                if (inetAddr()) {
                                    System.out
                                            .println("Net Connectivity is Present");
                                    isInternet = true;
                                    System.out.println("FOURTH");
                                } else {
                                    System.out
                                            .println("No Internet Connectivity");
                                isInternet = false;
                                    System.out.println("FIFTH");
                                }
                            } else {
                                System.out.println("No Internet Connectivity");
                                isInternet = false;
                                System.out.println("SIX");
                            }
                        }
                    }
                } catch (Exception ex) {
                    System.out.println("Leak ko catch");
                }

            }
        });
        t.start();
        try {
            t.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return isInternet;
    }


    public boolean checkConnection() {
        boolean connected = false;
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            NetworkInfo[] netInfo = cm.getAllNetworkInfo();
            for (NetworkInfo ni : netInfo) {
                if ((ni.getTypeName().equalsIgnoreCase("WIFI") || ni
                        .getTypeName().equalsIgnoreCase("MOBILE"))
                        & ni.isConnected() & ni.isAvailable()) {
                    connected = true;
                }
            }
        }
        return connected;
    }

    public boolean inetAddr() {
        boolean x1 = false;

        try {
            Socket s = new Socket();
            s.connect(new InetSocketAddress("ntp-nist.ldsbc.edu",37),3000);
            InputStream is = s.getInputStream();

            Scanner scan = new Scanner(is);

            while(scan.hasNextLine()){

                System.out.println(scan.nextLine());
                x1 = true;
            }
        } catch (IOException e) {

            x1 = false;

        }
        return x1;
    }
    public boolean mobileConnect() {
        boolean conn = false;
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNet = cm
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (activeNet != null) {
            conn = true;
        } else {
            conn = false;
        }
        return conn;
    }

    @SuppressWarnings("deprecation")
    private void myNotify(String text) {
        Notification notif = new Notification(R.drawable.ic_launcher, text, System
                .currentTimeMillis());
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,new Intent(this, MainActivity.class), 0);
        notif.setLatestEventInfo(this, "MotorVehicleApp", text, contentIntent);
        // notif.defaults = Notification.DEFAULT_VIBRATE;
        myNotificationManager.notify((int) System.currentTimeMillis(), notif);
    }

    @Override
    public void onCreate() {
        super.onCreate();


         String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

            if(!provider.contains("gps")){ //if gps is disabled
                final Intent poke = new Intent();
                poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
                poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
                poke.setData(Uri.parse("3")); 
                sendBroadcast(poke);
            }


        intent = new Intent(BROADCAST_ACTION);
        android.util.Log.d("MWD", "creating");
        myLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        System.out.println("location manager:"+myLocationManager.getAllProviders());
        myLocationProvider = myLocationManager.getProvider("gps");
        myNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        updatePreferences();
    }
    public void updatePreferences() {
        // sync local variables with preferences
        android.util.Log.d("NWD", "updating preferences");
        frequency = 10;
        // update the LM with the new frequency
        myLocationManager.removeUpdates(this);
        myLocationManager.requestLocationUpdates(myLocationProvider.getName(),frequency, 0, this);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        /////------set edittext editable        

         android.util.Log.d("NWD", "destroying");

         System.out.println("Inside on destroy of MWService");
         myLocationManager.removeUpdates(this);
        //myNotify("stopping");

        InsertTripDetails_AsyncTask insert = new InsertTripDetails_AsyncTask();
        insert.execute();

        String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

        if(provider.contains("gps")){ //if gps is enabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3")); 
            sendBroadcast(poke);
        }
        handler.removeCallbacks(sendUpdatesToUI);
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        android.util.Log.d("NWD", "starting");
        currentLocation = myLocationManager.getLastKnownLocation(myLocationProvider.getName());
        //myNotify("starting"); 

        handler.postDelayed(sendUpdatesToUI, 3000); // 1 sec

    }
    private Runnable sendUpdatesToUI = new Runnable() {
            public void run() {
                System.out.println("total_distance::"+total_distance);
                intent.putExtra("distance",(total_distance/1000));
                sendBroadcast(intent);
                handler.postDelayed(this, 3000);
            }
     };

    public void onProviderDisabled(String arg0) {

    }

    public void onProviderEnabled(String arg0) {

    }

    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {

    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null; // this is for heavy IPC, not used
    }
    private class InsertTripDetails_AsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {

            try {


                    try {
                        //InternetAvailable()
                        if(InternetAvailable()){
                            startAddress =  geocoder.fetchCityName(getApplicationContext(),startLocation);
                            System.out.println("start address:"+startAddress);
                            endAddress = geocoder.fetchCityName(getApplicationContext(),endLocation);
                            System.out.println("end address:"+endAddress);
                        }else{
                            System.out.println("internet not available");
                        }

                        // Internet not available when data are store in latitude and longitute format
                        if(startAddress.equalsIgnoreCase("") && endAddress.equalsIgnoreCase("")){
                            DecimalFormat sd = new DecimalFormat("##.##");
                            System.out.println("1 lat:"+sd.format(startLocation.getLatitude()) +" long:"+sd.format(startLocation.getLongitude())+",lat:"+sd.format(endLocation.getLatitude()) +" long:"+sd.format(endLocation.getLongitude()));

                        }else if(startAddress.equalsIgnoreCase("")){
                            DecimalFormat sd = new DecimalFormat("##.##");
                            System.out.println("2 lat:"+sd.format(startLocation.getLatitude()) +" long:"+sd.format(startLocation.getLongitude())+","+endAddress);

                        }else if(endAddress.equalsIgnoreCase("")){
                            DecimalFormat sd = new DecimalFormat("##.##");
                            try {
                                System.out.println(startAddress+",3 lat:"+sd.format(endLocation.getLatitude()) +" long:"+sd.format(endLocation.getLongitude()));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        else{
                            System.out.println(startAddress+" "+ endAddress);
                        }



                    } catch (Exception e) {
                    e.printStackTrace();
                  }



                    } catch (Exception e) {

                        e.printStackTrace();
                        System.out.println("In catch of webservice thus no internet");

                    }


            return "dfs";
                }
                @Override
                protected void onPostExecute(String result) {

                }
    }

}

// ---------- MainActivity.java ---------------

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(MainActivity.this,MWService.class));
    }

    @Override
    protected void onPause() {
            super.onPause();
            stopService(new Intent(MainActivity.this,MWService.class));
    }

}

// -------------------的AndroidManifest.xml ----------

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="10" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.android.MainActivity"
            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:name="MWService"></service>
    </application>

</manifest>

// ------------- main.xml中--------------

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >


</RelativeLayout>

// ---把处理程序代码看下面的图像

enter image description here

私有final Handler handler = new Handler(); 在类变量中。