使用Web服务在Android中获得地址 [英] getting address in android using web service

查看:160
本文介绍了使用Web服务在Android中获得地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

IAM新的Andr​​oid开发。

我已经尝试使用Web服务来获取位置的地址,但我得到的类未发现异常,当我这吃午餐code.如果任何人能请建议我,这妥善解决。

code为服务类....

 公共类MWService扩展服务实现LocationListener的{
私人的LocationManager myLocationManager;
私人LocationProvider myLocationProvider;
私人NotificationManager myNotificationManager;
私人长期频率;
私人双total_distance = 0;
私人位置currentLocation;
公共静态最后弦乐BROADCAST_ACTION =com.motorvehicle.android;
私人最终处理程序处理程序=新的处理程序();
意图意图;
私家地理coderHelper地理codeR =新的地缘coderHelper();
私人布尔ISSTART = TRUE;
私人位置startLocation,EndLocation组件;
私人字符串startAddress =;
私人字符串endAddress =;
私人JSONArray jarray =新JSONArray();
私人布尔isInternet;
//私人最终处理程序处理程序=新的处理程序();公共无效onLocationChanged(位置newLocation){
    尝试{
        的System.out.println(纬度电流:+ currentLocation.getLatitude());
        的System.out.println(纬度电流:+ currentLocation.getLongitude());
        的System.out.println(新纬度:+ newLocation.getLatitude());
        的System.out.println(新纬度:+ newLocation.getLongitude());
        的System.out.println(距离总:+ total_distance);
        //System.out.println(distance(22.306813,73.180239,22.301016,73.177986,K)+公里\\ n);
        双差异= 0.0;
        的diff = currentLocation.getLatitude() - newLocation.getLatitude();
        的System.out.println(差异化::+差异);
        如果(差异!= 0){
            total_distance = total_distance + currentLocation.distanceTo(newLocation);
        }
        如果(ISSTART){
            ISSTART = FALSE;
            startLocation = newLocation;
        / *如果(InternetAvailable()){
                // startAddress =地理coder.fetchCityName(getApplicationContext(),newLocation);
                的System.out.println(起始地址:+ startAddress);
            } * /        }其他{
            EndLocation组件= newLocation;
            / *如果(InternetAvailable()){
                // endAddress =地理coder.fetchCityName(getApplicationContext(),newLocation);
                的System.out.println(endAddress:+ endAddress);
            } * /
        }        currentLocation = newLocation;
    }赶上(例外五){
        currentLocation = newLocation;
        e.printStackTrace();
    }
}公共布尔InternetAvailable(){    线程t =新主题(新的Runnable(){
        @覆盖
        公共无效的run(){
            //而(isStopMe){
            的System.out.println(这里面.................:);
            尝试{
                如果(!checkConnection()){
                    的System.out.println(无Internet连接);
                    isInternet = FALSE;
                    的System.out.println(第一);
                }其他{
                    如果(的InetAddr()){
                        的System.out.println(网络连通性是present);
                        isInternet = TRUE;
                        的System.out.println(二);
                    }其他{
                        如果(MobileConnect的()){
                            的System.out.println(第三);
                            如果(的InetAddr()){
                                System.out的
                                        .println(网络连通性是present);
                                isInternet = TRUE;
                                的System.out.println(第四);
                            }其他{
                                System.out的
                                        .println(无Internet连接);
                            isInternet = FALSE;
                                的System.out.println(十五);
                            }
                        }其他{
                            的System.out.println(无Internet连接);
                            isInternet = FALSE;
                            的System.out.println(六个一);
                        }
                    }
                }
            }赶上(例外前){
                的System.out.println(泄漏こ捕);
            }        }
    });
    t.start();
    尝试{
        t.join();
    }赶上(InterruptedException的E){
        // TODO自动生成catch块
        e.printStackTrace();
    }
    返回isInternet;
}
公共布尔checkConnection(){
    布尔连接= FALSE;
    ConnectivityManager厘米=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    如果(厘米!= NULL){
        的NetworkInfo [] = NetInfo的cm.getAllNetworkInfo();
        对于(NI的NetworkInfo:NetInfo的){
            如果((ni.getTypeName()。equalsIgnoreCase(WIFI)||妮
                    .getTypeName()。equalsIgnoreCase(手机))
                    &安培; ni.isConnected()及ni.isAvailable()){
                连接= TRUE;
            }
        }
    }
    返回连接;
}公共布尔的InetAddr(){
    布尔X1 = FALSE;    尝试{
        插座S =新的Socket();
        s.connect(新的InetSocketAddress(ntp-nist.ldsbc.edu,37),3000);
        InputStream为= s.getInputStream();        扫描程序扫描=新的扫描仪(是);        而(scan.hasNextLine()){            的System.out.println(scan.nextLine());
            X1 = TRUE;
        }
    }赶上(IOException异常五){        X1 = FALSE;    }
    返回X1;
}
公共布尔MobileConnect的(){
    布尔康恩= FALSE;
    ConnectivityManager厘米=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    的NetworkInfo activeNet =厘米
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    如果(activeNet!= NULL){
        康恩=真;
    }其他{
        康恩= FALSE;
    }
    康涅狄格州返回;
}@燮pressWarnings(德precation)
私人无效myNotify(字符串文本){
    注意notif =新的通知(R.drawable.ic_launcher,文本,系统
            .currentTimeMillis());
    的PendingIntent contentIntent = PendingIntent.getActivity(在此,0,新意图(此,MainActivity.class),0);
    notif.setLatestEventInfo(这一点,MotorVehicleApp,文字,contentIntent);
    // notif.defaults = Notification.DEFAULT_VIBRATE;
    myNotificationManager.notify((INT)System.currentTimeMillis的(),notif);
}@覆盖
公共无效的onCreate(){
    super.onCreate();
     字符串提供商= Settings.Secure.getString(getContentResolver(),Settings.Secure.LOCATION_PROVIDERS_ALLOWED);        如果(!provider.contains(GPS)){//如果GPS被禁用
            最终意图捅=新意图();
            poke.setClassName(com.android.settings,com.android.settings.widget.SettingsAppWidgetProvider);
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse(3));
            sendBroadcast(捅);
        }
    意图=新意图(BROADCAST_ACTION);
    android.util.Log.d(MWD,创造);
    myLocationManager =(的LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
    的System.out.println(位置经理:+ myLocationManager.getAllProviders());
    myLocationProvider = myLocationManager.getProvider(GPS);
    myNotificationManager =(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
    更新preferences();    handler.post(新的Runnable(){
        @覆盖公共无效的run(){
            Toast.makeText(getApplicationContext(),地址:+ startAddress,Toast.LENGTH_LONG).show(); }});
}
公共无效更新preferences(){
    //同步局部变量与preferences
    android.util.Log.d(新世界发展,更新preferences);
    频率= 10;
    //更新为新的频率在LM
    myLocationManager.removeUpdates(本);
    myLocationManager.requestLocationUpdates(myLocationProvider.getName(),频率,0,这一点);
}
@覆盖
公共无效的onDestroy(){
    super.onDestroy();
    ///// ------设置可编辑的EditText     android.util.Log.d(新世界发展,破坏);     的System.out.println(内部的消灭MWService的);
     myLocationManager.removeUpdates(本);
    // myNotify(停止);    InsertTripDetails_AsyncTask插入=新InsertTripDetails_AsyncTask();
    insert.execute();    字符串提供商= Settings.Secure.getString(getContentResolver(),Settings.Secure.LOCATION_PROVIDERS_ALLOWED);    如果(provider.contains(GPS))如果启用GPS {//
        最终意图捅=新意图();
        poke.setClassName(com.android.settings,com.android.settings.widget.SettingsAppWidgetProvider);
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse(3));
        sendBroadcast(捅);
    }
    handler.removeCallbacks(sendUpdatesToUI);
}@燮pressWarnings(德precation)
@覆盖
公共无效调用onStart(意向意图,诠释startId){
    super.onStart(意向,startId);
    android.util.Log.d(新世界发展,出发);
    currentLocation = myLocationManager.getLastKnownLocation(myLocationProvider.getName());
    // myNotify(启动);    handler.postDelayed(sendUpdatesToUI,3000); // 1秒}
私人Runnable接口sendUpdatesToUI =新的Runnable(){
        公共无效的run(){
            的System.out.println(total_distance ::+ total_distance);
            intent.putExtra(距离,(total_distance / 1000));
            sendBroadcast(意向);
            handler.postDelayed(这一点,3000);
        }
 };公共无效onProviderDisabled(字符串为arg0){}公共无效onProviderEnabled(字符串为arg0){}公共无效onStatusChanged(字符串为arg0,ARG1 INT,捆绑ARG2){}@覆盖
公众的IBinder onBind(意向为arg0){
    返回null; //这是沉重的工控机,不使用
}
私有类InsertTripDetails_AsyncTask扩展的AsyncTask<弦乐,太虚,字符串> {    @覆盖
    保护字符串doInBackground(字符串的URL ...){        尝试{
                尝试{
                    // InternetAvailable()
                    如果(InternetAvailable()){
                        startAddress =地理coder.fetchCityName(getApplicationContext(),startLocation);
                        的System.out.println(起始地址:+ startAddress);
                        endAddress =地理coder.fetchCityName(getApplicationContext(),EndLocation组件);
                        的System.out.println(结束地址:+ endAddress);
                    }其他{
                        的System.out.println(网络不可用);
                    }                    //上网的时候数据是存储在纬度和经度格式不可用
                    如果(startAddress.equalsIgnoreCase()及与放大器; endAddress.equalsIgnoreCase()){
                        DecimalFormat的SD =新DecimalFormat的(## ##);
                        的System.out.println(1纬度:+ sd.format(startLocation.getLatitude())+长:+ sd.format(startLocation.getLongitude())+,纬度:+ sd.format(EndLocation组件.getLatitude())+长:+ sd.format(endLocation.getLongitude()));                    }否则如果(startAddress.equalsIgnoreCase()){
                        DecimalFormat的SD =新DecimalFormat的(## ##);
                        的System.out.println(2纬度:+ sd.format(startLocation.getLatitude())+长:+ sd.format(startLocation.getLongitude())+,+ endAddress);                    }否则如果(endAddress.equalsIgnoreCase()){
                        DecimalFormat的SD =新DecimalFormat的(## ##);
                        尝试{
                            的System.out.println(startAddress +,3纬度:+ sd.format(endLocation.getLatitude())+长:+ sd.format(endLocation.getLongitude()));
                        }赶上(例外五){
                            e.printStackTrace();
                        }
                    }
                    其他{
                        的System.out.println(startAddress ++ endAddress);
                    }                }赶上(例外五){
                e.printStackTrace();
              }                }赶上(例外五){                    e.printStackTrace();
                    的System.out.println(在Web服务因而没有互联网的捕);                }
        返回DFS
            }
            @覆盖
            保护无效onPostExecute(字符串结果){            }
}}

code为地理codeR类

 公共类地理coderHelper
{
私有静态最终AndroidHttpClient ANDROID_HTTP_CLIENT = AndroidHttpClient.newInstance(GEO coderHelper.class.getName());私人字符串的地址=;
私人位置i_Location;
私人语境i_Context;
公共字符串fetchCityName(最终上下文CONTEX,最终定位位置)
{
    i_Location =位置;
    i_Context = CONTEX;
  尝试{
        返回新地址()的execute()得到()。
    }赶上(例外五){        退货地址;    }
}公共类地址扩展的AsyncTask<太虚,太虚,字符串>
{    @燮pressWarnings(未使用)
    @覆盖
    保护字符串doInBackground(无效... PARAMS)
    {
        字符串的cityName = NULL;        如果(GEO coder.is present())
        {
            尝试
            {
                的System.out.println(位置纬度为+ i_Location.getLatitude());
                的System.out.println(所在地经度为+ i_Location.getLongitude());                地理codeR地理codeR =新的地缘codeR(i_Context,Locale.getDefault());
                清单< android.location.Address>地址=地理coder.getFromLocation(i_Location.getLatitude(),i_Location.getLongitude(),1);
                如果(addresses.size()大于0)
                {
                    //的cityName = addresses.get(0).getLocality();
                    地址= addresses.get(0).getLocality();
                    的System.out.println(地理$ C $ present地址里面CR是+地址);                }
            }
            赶上(异常忽略)
            {
                //过了一会儿,地理codeR开始trhow服务不availalbe异常。很奇怪,因为在此之前(同一设备,同一Android版本等工作..
            }
        }        如果(的cityName!= NULL)//即地理codeR成功
        {
            返回的cityName;
        }
        否则//即地理codeR失败
        {
            返回fetchCityNameUsingGoogleMap();
        }    }    //地理codeR失败:-(
    //我们的B计划:谷歌地图
    私人字符串fetchCityNameUsingGoogleMap()
    {
        尝试
        {
            串googleMapUrl =htt​​p://maps.googleapis.com/maps/api/geo$c$c/json?latlng=+ i_Location.getLatitude()+,
                    + i_Location.getLongitude()+&放大器;传感器=假放,语言= zh的;            JSONObject的googleMa presponse =新的JSONObject(ANDROID_HTTP_CLIENT.execute(新HTTPGET(googleMapUrl)
                    新BasicResponseHandler()));            //许多嵌套循环..不是很大 - >使用前pression代替
            //所有结果中环
            JSONArray结果=(JSONArray),其中googleMa presponse.get(结果);
            的for(int i = 0; I< results.length();我++)
            {
                //这个结果中的所有地址中环
                的JSONObject结果= results.getJSONObject(ⅰ);
                地址= result.getString(的formatted_address);
                的System.out.println(地图地址:+地址);
                打破;      / *如果(result.has(address_components))
                {
                    JSONArray addressComponents = result.getJSONArray(address_components);
                    //所有地址组件中环找一个'地方'或'sublocality
                    对于(INT J = 0; J< addressComponents.length(); J ++)
                    {
                        JSONObject的addressComponent = addressComponents.getJSONObject(J);
                        如果(result.has(类型))
                        {
                            JSONArray类型= addressComponent.getJSONArray(类型);                            //搜索本地和sublocality
                            字符串的cityName = NULL;
                            字符串ROUTE = NULL;                            对于(INT K = 0; K< types.length(); K ++)
                            {                                如果(局部性.equals(types.getString(K))及和放大器;的cityName == NULL)
                                {
                                    如果(addressComponent.has(LONG_NAME))
                                    {
                                        的cityName = addressComponent.getString(LONG_NAME);
                                    }
                                    否则如果(addressComponent.has(SHORT_NAME))
                                    {
                                        的cityName = addressComponent.getString(简称的);
                                    }
                                }
                                如果(sublocality.equals(types.getString(K)))
                                {
                                    如果(addressComponent.has(LONG_NAME))
                                    {
                                        的cityName = addressComponent.getString(LONG_NAME);
                                    }
                                    否则如果(addressComponent.has(SHORT_NAME))
                                    {
                                        的cityName = addressComponent.getString(简称的);
                                    }
                                }
                            }
                            如果(的cityName!= NULL)
                            {
                                地址=的cityName;
                                返回的cityName;                            }
                        }
                    }
                } * /
            }
        }
        赶上(异常忽略)
        {
            ignored.printStackTrace();
        }
        退货地址;
    }    保护无效onPostExecute(字符串结果)
    {          super.onPostExecute(结果);
    }
}
}

code为MainActivity类别

 公共类MainActivity延伸活动{
//私人最终处理程序处理程序=新的处理程序();@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);
    startService(新意图(MainActivity.this,MWService.class));}@覆盖
保护无效的onPause(){
        super.onPause();
        stopService(新意图(MainActivity.this,MWService.class));
}}

我对互联网和AccessFineLocation

在我menifest文件使用权限

我的logcat味精......

  10-31 13:40:41.937:ERROR / AndroidRuntime(825):了java.lang.RuntimeException:无法实例活动ComponentInfo {com.example.address2 / com。示例。 android.MainActivity}:抛出java.lang.ClassNotFoundException:com.example.android.MainActivity装载机dalvik.system.PathClassLoader [/data/app/com.example.address2-1.apk]
10-31 13:40:41.937:ERROR / AndroidRuntime(825):抛出java.lang.ClassNotFoundException:致com.example.android.MainActivity装载机dalvik.system.PathClassLoader [/data/app/com.example.address2 -1.apk]

code为我menifest文件....

 <采用-SDK
    安卓的minSdkVersion =10
    机器人:targetSdkVersion =17/>
 <使用许可权的android:NAME =android.permission.INTERNET对/>
<使用许可权的android:NAME =android.permission.ACCESS_FINE_LOCATION/><应用
    机器人:allowBackup =真
    机器人:图标=@绘制/ ic_launcher
    机器人:标签=@字符串/ APP_NAME
    机器人:主题=@风格/ AppTheme>
    <活动
        机器人:名字=com.example.android.MainActivity
        机器人:标签=@字符串/ APP_NAME>
        &所述;意图滤光器>
            <作用机器人:名字=android.intent.action.MAIN/>            <类机器人:名字=android.intent.category.LAUNCHER/>
        &所述; /意图滤光器>
    < /活性GT;
    <服务机器人:名字=MWService>< /服务>
< /用途>


解决方案

使用我的code。我已经成功地找到使用坐标我目前的地址,但对于您必须启用WIFI和GPS。
首先添加所有这些权限在你的Andr​​oid清单文件

 <使用许可权的android:NAME =android.permission.INTERNET对/>
<使用许可权的android:NAME =android.permission.ACCESS_NETWORK_STATE/>
<使用许可权的android:NAME =android.permission.CHANGE_NETWORK_STATE/>
<使用许可权的android:NAME =android.permission.ACCESS_WIFI_STATE/>
<使用许可权的android:NAME =android.permission.CHANGE_WIFI_STATE/>
<使用许可权的android:NAME =android.permission.WAKE_LOCK/>
<使用许可权的android:NAME =android.permission.ACCESS_COARSE_LOCATION/>
<使用许可权的android:NAME =android.permission.ACCESS_FINE_LOCATION/>

AndroidGPSTrackingActivity.java *

 包com.example.gpstracking;进口java.io.IOException异常;
进口java.lang.reflect.InvocationTargetException;
进口的java.lang.reflect.Method;
进口的java.util.List;
进口java.util.Locale中;进口android.app.Activity;
进口android.content.Context;
进口android.content.Intent;
进口android.location.Address;
进口android.location.Geo codeR;
进口android.location.LocationManager;
进口android.net.ConnectivityManager;
进口android.net.Uri;
进口android.net.wifi.WifiManager;
进口android.os.Bundle;
进口android.view.View;
进口android.webkit.WebView;
进口android.widget.Button;
进口android.widget.CompoundButton;
进口android.widget.CompoundButton.OnCheckedChangeListener;
进口android.widget.Toast;
进口android.widget.ToggleButton;公共类AndroidGPSTrackingActivity延伸活动{    按钮btnShowLocation;    // GPSTracker类
    GPSTracker GPS;
    切换按钮gpstoggle,wifitoggle,datatoggle;
    静态WifiManager wifiManager;
    LM的LocationManager;
    的WebView网络;
    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);        btnShowLocation =(按钮)findViewById(R.id.btnShowLocation);        gpstoggle =(切换按钮)findViewById(R.id.gps);
        wifitoggle =(切换按钮)findViewById(R.id.wifi);        wifiManager =(WifiManager)this.getSystemService(Context.WIFI_SERVICE);        LM =(的LocationManager)getSystemService(LOCATION_SERVICE);        // GPS切换
        gpstoggle.setOnCheckedChangeListener(新OnCheckedChangeListener(){            @覆盖
            公共无效onCheckedChanged(CompoundButton buttonView,布尔器isChecked){
                如果(器isChecked){
                    最终意图捅=新意图();
                    poke.setClassName(com.android.settings,com.android.settings.widget.SettingsAppWidgetProvider);
                    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
                    poke.setData(Uri.parse(3));
                    。getApplicationContext()sendBroadcast(捅);
                }
                其他{
                    最终意图捅=新意图();
                    poke.setClassName(com.android.settings,com.android.settings.widget.SettingsAppWidgetProvider);
                    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
                    poke.setData(Uri.parse(3));
                    。getApplicationContext()sendBroadcast(捅);
                }
            }
        });
        // WiFi切换
        wifitoggle.setOnCheckedChangeListener(新OnCheckedChangeListener(){            @覆盖
            公共无效onCheckedChanged(CompoundButton buttonView,布尔器isChecked){
                如果(器isChecked){
                    wifiManager.setWifiEnabled(真);
                }
                其他{
                    wifiManager.setWifiEnabled(假);
                }
            }
        });        //数据触发
        datatoggle.setOnCheckedChangeListener(新OnCheckedChangeListener(){            @覆盖
            公共无效onCheckedChanged(CompoundButton buttonView,布尔器isChecked){
                如果(器isChecked){
                    ConnectivityManager DATAMANAGER;
                    DATAMANAGER =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
                    方法dataMtd = NULL;                    尝试{
                        dataMtd = ConnectivityManager.class.getDeclaredMethod(setMobileDataEnabled,boolean.class);
                        dataMtd.setAccessible(真);
                        dataMtd.invoke(DATAMANAGER,真);                    }赶上(NoSuchMethodException E1){
                        e1.printStackTrace();
                    }
                    赶上(抛出:IllegalArgumentException五){
                        e.printStackTrace();
                    }赶上(IllegalAccessException E){
                        e.printStackTrace();
                    }赶上(的InvocationTargetException E){
                        e.printStackTrace();
                    }
                    赶上(SecurityException异常五){
                        e.printStackTrace();
                    }                }
                其他{
                    ConnectivityManager DATAMANAGER;
                    DATAMANAGER =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
                    方法dataMtd = NULL;                    尝试{
                        dataMtd = ConnectivityManager.class.getDeclaredMethod(setMobileDataEnabled,boolean.class);
                        dataMtd.setAccessible(假);
                        dataMtd.invoke(DATAMANAGER,FALSE);
                    }赶上(NoSuchMethodException E1){
                        e1.printStackTrace();
                    }
                    赶上(抛出:IllegalArgumentException五){
                        e.printStackTrace();
                    }赶上(IllegalAccessException E){
                        e.printStackTrace();
                    }赶上(的InvocationTargetException E){
                        e.printStackTrace();
                    }
                    赶上(SecurityException异常五){
                        e.printStackTrace();
                    }                }
            }
        });        //展示位置按钮单击事件
        btnShowLocation.setOnClickListener(新View.OnClickListener(){            @覆盖
            公共无效的onClick(查看为arg0){
                //创建类对象
                GPS =新GPSTracker(AndroidGPSTrackingActivity.this);                //检查是否启用GPS
                如果(gps.canGetLocation()){                    双纬度= gps.getLatitude();
                    双经度= gps.getLongitude();                    地理codeR GCD =新的地缘codeR(getApplicationContext(),Locale.getDefault());
                    清单<地址>地址= NULL;
                    尝试{
                        地址= gcd.getFromLocation(纬度,经度,1);
                    }赶上(IOException异常五){
                        // TODO自动生成catch块
                        e.printStackTrace();
                    }
                    如果(!(地址== NULL)){
                        如果(!addresses.isEmpty()){
                            的System.out.println(addresses.get(0).getLocality());                            地址地址= addresses.get(0);                            字符串addressText =的String.format(%S%S%S,%S%S%S,
                                    address.getAddressLine(0),
                                    address.getAddressLine(1),
                                    address.getAddressLine(2),
                                    address.getAddressLine(3),
                                    address.getPhone(),
                                    address.get premises());                            的System.out.println(addressText);                            // \\ n是新行
                            Toast.makeText(getApplicationContext(),您现在的位置是 - \\ nLat:+纬度+\\ nLong:+经度,Toast.LENGTH_LONG).show();
                        }其他{
                            //无法获取位置
                            未启用// GPS或网络
                            //要求用户在设置中启用GPS /网络
                            gps.showSettingsAlert();
                        }
                    }其他{
                        //无法获取位置
                        未启用// GPS或网络
                        //要求用户在设置中启用GPS /网络
                        gps.showSettingsAlert();
                    }                }            }
        });
    }}

GPSTracker.java

 包com.example.gpstracking;进口android.app.AlertDialog;
进口android.app.Service;
进口android.content.Context;
进口android.content.DialogInterface;
进口android.content.Intent;
进口android.location.Location;
进口android.location.LocationListener;
进口android.location.LocationManager;
进口android.net.ConnectivityManager;
进口android.net.NetworkInfo;
进口android.net.wifi.WifiManager;
进口android.os.Bundle;
进口android.os.IBinder;
进口android.provider.Settings;
进口android.util.Log;
进口android.widget.Toast;公共类GPSTracker扩展服务实现LocationListener的{    私人最终上下文mContext;    //标志GPS状态
    布尔isGPSEnabled = FALSE;    //标志GPS状态
    布尔canGetLocation = FALSE;    地点位置; // 位置
    双纬度; //纬度
    双经度; //经度    //最小距离改变米的更新
    私有静态最后长MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10米    //毫秒更新之间的最短时间
    私有静态最后长MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1分钟    //声明一个位置管理
    受保护的LocationManager的LocationManager;    公共GPSTracker(上下文的背景下){
        this.mContext =背景;
        的getLocation();
    }    公共场所的getLocation(){
        尝试{
            的LocationManager =(的LocationManager)mContext.getSystemService(LOCATION_SERVICE);            //获取GPS状态
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);            //获取网络状态
            布尔wifiEnabled = AndroidGPSTrackingActivity.wifiManager.isWifiEnabled();            ConnectivityManager厘米=(ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            的NetworkInfo activeNetwork = cm.getActiveNetworkInfo();            this.canGetLocation = TRUE;            //如果数据可得拉/长使用WIFI服务
            如果(activeNetwork.isConnected()){
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES,这一点);
                Log.d(网络,网络);
                如果(的LocationManager!= NULL){
                    位置=的LocationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);                }
            }
            //如果WiFi功能得到纬度/长使用WIFI服务
            如果(wifiEnabled){
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES,这一点);
                Log.d(网络,网络);
                如果(的LocationManager!= NULL){
                    位置=的LocationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);                }
            }
            //如果GPS功能的获得纬度/长期使用GPS服务
            如果(isGPSEnabled){
                如果(位置== NULL){
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES,这一点);
                    Log.d(GPS已启用,GPS功能的);
                    如果(的LocationManager!= NULL){
                        位置=的LocationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);                    }
                }
            }
            如果(位置!= NULL){
                纬度= location.getLatitude();
                经度= location.getLongitude();
            }        }赶上(例外五){
            e.printStackTrace();
        }        返回的位置;
    }    / **
     *停止使用GPS监听器
     *调用此函数将停止在你的应用程序中使用GPS
     * * /
    公共无效stopUsingGPS(){
        如果(的LocationManager!= NULL){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }    / **
     *函数来获取纬度
     * * /
    公共双getLatitude(){
        如果(位置!= NULL){
            纬度= location.getLatitude();
        }        //返回纬度
        返回纬度;
    }    / **
     *函数来获取经度
     * * /
    公共双getLongitude(){
        如果(位置!= NULL){
            经度= location.getLongitude();
        }        //返回经度
        返回经度;
    }    / **
     *功能检查启用GPS / WIFI
     * @返回布尔
     * * /
    公共布尔canGetLocation(){
        返回this.canGetLocation;
    }    / **
     *功能,以显示设置警告对话框
     *在pressing设置按钮将劳克设置选项
     * * /
    公共无效showSettingsAlert(){
        AlertDialog.Builder alertDialog =新AlertDialog.Builder(mContext);        //设置对话框标题
        alertDialog.setTitle(GPS是设置);        //设置对话框留言
        alertDialog.setMessage(GPS未启用你想要去设置菜单?);        //在pressing设置按钮
        alertDialog.setPositiveButton(设置,新DialogInterface.OnClickListener(){
            公共无效的onClick(DialogInterface对话,诠释它){
                意向意图=新意图(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(意向);
            }
        });        //在pressing取消按钮
        alertDialog.setNegativeButton(取消,新DialogInterface.OnClickListener(){
            公共无效的onClick(DialogInterface对话,诠释它){
                dialog.cancel();
            }
        });        //显示警报信息
        alertDialog.show();
    }    @覆盖
    公共无效onLocationChanged(地点){
    }    @覆盖
    公共无效onProviderDisabled(字符串提供商){
    }    @覆盖
    公共无效onProviderEnabled(字符串提供商){
    }    @覆盖
    公共无效onStatusChanged(字符串提供商,INT地位,捆绑演员){
    }    @覆盖
    公众的IBinder onBind(意向为arg0){
        返回null;
    }}

的main.xml

 <?XML版本=1.0编码=UTF-8&GT?;
<的RelativeLayout的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =FILL_PARENT
    机器人:方向=垂直>    <按钮机器人:ID =@ + ID / btnShowLocation
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:文本=显示的位置
        机器人:layout_centerVertical =真
        机器人:layout_centerHorizo​​ntal =真/>    <切换按钮
        机器人:ID =@ + ID / GPS
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_above =@ + ID / btnShowLocation
        机器人:layout_alignRight =@ + ID / btnShowLocation
        机器人:layout_marginBottom =49dp
        机器人:layout_marginRight =72dp
        机器人:文字=GPS
         />    <切换按钮
        机器人:ID =@ + ID / WIFI
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_alignBaseline =@ + ID / GPS
        机器人:layout_alignBottom =@ + ID / GPS
        机器人:layout_alignLeft =@ + ID / btnShowLocation
        机器人:layout_marginLeft =79dp
        机器人:文字=WIFI/>    <的TextView
        机器人:ID =@ + ID / textView1
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_above =@ + ID / GPS
        机器人:layout_alignLeft =@ + ID / btnShowLocation
        机器人:文字=GPS
        机器人:TEXTSIZE =15sp/>    <的TextView
        机器人:ID =@ + ID / textView2
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_alignBaseline =@ + ID / textView1
        机器人:layout_alignBottom =@ + ID / textView1
        机器人:layout_marginLeft =61dp
        机器人:layout_toRightOf =@ + ID / textView1
        机器人:文字=WIFI
        机器人:TEXTSIZE =15sp/>< / RelativeLayout的>

iam new to android development.

i have tried to get location address using web service but i got class not found exception when i lunched this code.if any one could please suggest me proper solution for this..

code for service class....

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;
//private final Handler handler = new Handler();

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();



    handler.post(new Runnable() {
        @Override public void run() { 
            Toast.makeText(getApplicationContext(), "Address:"+startAddress, Toast.LENGTH_LONG).show(); } });
}
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) {

            }
}

}

code for geocoder class

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);
    }
}
}

code for MAinActivity class

public class MainActivity extends Activity {
//private final Handler handler = new Handler();

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



}

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

}

i have use permission in my menifest file for both internet and AccessFineLocation

my logcat msg.....

10-31 13:40:41.937: ERROR/AndroidRuntime(825): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.address2/com.example.android.MainActivity}: java.lang.ClassNotFoundException: com.example.android.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.address2-1.apk]
10-31 13:40:41.937: ERROR/AndroidRuntime(825): Caused by: java.lang.ClassNotFoundException: com.example.android.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.address2-1.apk]

code for my menifest file....

<uses-sdk
    android:minSdkVersion="10"
    android:targetSdkVersion="17" />
 <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>

解决方案

Use my Code. I have successfully found my current address using coordinates but for that you have to enable wifi and gps. first add all these permissions in your android manifest file

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

AndroidGPSTrackingActivity.java*

package com.example.gpstracking;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;

public class AndroidGPSTrackingActivity extends Activity {

    Button btnShowLocation;

    // GPSTracker class
    GPSTracker gps;
    ToggleButton gpstoggle,wifitoggle,datatoggle;
    static WifiManager wifiManager;
    LocationManager lm;
    WebView web;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

        gpstoggle = (ToggleButton) findViewById(R.id.gps);
        wifitoggle = (ToggleButton) findViewById(R.id.wifi);

        wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); 

        lm = (LocationManager) getSystemService(LOCATION_SERVICE);

        //gps toggle
        gpstoggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    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")); 
                    getApplicationContext().sendBroadcast(poke);
                }
                else{
                    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")); 
                    getApplicationContext().sendBroadcast(poke);
                }
            }
        });
        //wifi toggle
        wifitoggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    wifiManager.setWifiEnabled(true);
                }
                else{
                    wifiManager.setWifiEnabled(false);
                }
            }
        });

        //data toggle
        datatoggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    ConnectivityManager dataManager;
                    dataManager  = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
                    Method dataMtd = null;

                    try {
                        dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
                        dataMtd.setAccessible(true);
                        dataMtd.invoke(dataManager, true);

                    } catch (NoSuchMethodException e1) {
                        e1.printStackTrace();
                    }
                    catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }  
                    catch (SecurityException e) {
                        e.printStackTrace();
                    } 

                }
                else{
                    ConnectivityManager dataManager;
                    dataManager  = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
                    Method dataMtd = null;

                    try {
                        dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
                        dataMtd.setAccessible(false);
                        dataMtd.invoke(dataManager, false);


                    } catch (NoSuchMethodException e1) {
                        e1.printStackTrace();
                    }
                    catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }  
                    catch (SecurityException e) {
                        e.printStackTrace();
                    } 

                }
            }
        });

        // show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {        
                // create class object
                gps = new GPSTracker(AndroidGPSTrackingActivity.this);

                // check if GPS enabled     
                if(gps.canGetLocation()){

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                    Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
                    List<Address> addresses = null;
                    try {
                        addresses = gcd.getFromLocation(latitude, longitude, 1);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if(!(addresses == null)){
                        if (!addresses.isEmpty() ){
                            System.out.println(addresses.get(0).getLocality());

                            Address address = addresses.get(0);

                            String addressText = String.format("%s, %s, %s, %s, %s, %s",
                                    address.getAddressLine(0),
                                    address.getAddressLine(1),
                                    address.getAddressLine(2),
                                    address.getAddressLine(3),
                                    address.getPhone(),
                                    address.getPremises());

                            System.out.println(addressText);

                            // \n is for new line
                            Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                        }else{
                            // can't get location
                            // GPS or Network is not enabled
                            // Ask user to enable GPS/network in settings
                            gps.showSettingsAlert();
                        }
                    }else{
                        // can't get location
                        // GPS or Network is not enabled
                        // Ask user to enable GPS/network in settings
                        gps.showSettingsAlert();
                    }

                }

            }
        });
    }

}

GPSTracker.java

package com.example.gpstracking;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = 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

    // 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
            boolean wifiEnabled = AndroidGPSTrackingActivity.wifiManager.isWifiEnabled();

            ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

            this.canGetLocation = true;

            // if DATA Enabled get lat/long using WIFI Services
            if (activeNetwork.isConnected()) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_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 WIFI Enabled get lat/long using WIFI Services
            if (wifiEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_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 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) {
    }

    @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;
    }

}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button android:id="@+id/btnShowLocation" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Location"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>

    <ToggleButton
        android:id="@+id/gps"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnShowLocation"
        android:layout_alignRight="@+id/btnShowLocation"
        android:layout_marginBottom="49dp"
        android:layout_marginRight="72dp"
        android:text="GPS"
         />

    <ToggleButton
        android:id="@+id/wifi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/gps"
        android:layout_alignBottom="@+id/gps"
        android:layout_alignLeft="@+id/btnShowLocation"
        android:layout_marginLeft="79dp"
        android:text="WIFI" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/gps"
        android:layout_alignLeft="@+id/btnShowLocation"
        android:text="GPS"
        android:textSize="15sp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView1"
        android:layout_alignBottom="@+id/textView1"
        android:layout_marginLeft="61dp"
        android:layout_toRightOf="@+id/textView1"
        android:text="WIFI"
        android:textSize="15sp" />

</RelativeLayout>

这篇关于使用Web服务在Android中获得地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆