在android应用程序中使用BroadCastReceiver获取纬度和经度?

发布于 2024-12-25 22:24:45 字数 7397 浏览 0 评论 0原文

海是 Android 应用程序的新手,正在尝试使用广播接收器获取纬度和经度。但是我的应用程序正在强制关闭。我不知道为什么会发生这种情况。请任何人纠正我的错误。

        @Override
        public void onClick(View v) 
        {
             locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
             // Define the criteria how to select the locatioin provider -> use
             // default
             Criteria criteria = new Criteria();

         provider = locationManager.getBestProvider(criteria, false);
         Location location = locationManager.getLastKnownLocation(provider);

         // Initialize the location fields
         if (location != null) {
            System.out.println("Provider " + provider + " has been selected.");
            float lat = (float) (location.getLatitude());
            float lng = (float) (location.getLongitude());
            latituteField.setText(String.valueOf(lat));
            longitudeField.setText(String.valueOf(lng));

         } else {
            latituteField.setText("provider not available");
            longitudeField.setText("provider not available");
         }
            registerReceiver(receiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
        }
    });

        private class ConnectivityReceiver extends BroadcastReceiver{

            @Override
            public void onReceive(Context context, Intent intent) {
                    NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

                    if(null != info)
                    {
                            String state = getNetworkStateString(info.getState());
                            String stateString = info.toString().replace(',', '\n');
                            if(state.equals("Connected")){
                                result();

                            }

                    }
            }

}
    @Override
    protected void onResume() {
        super.onResume();
        //locationManager.requestLocationUpdates(provider,1000, 1, this);
        locationManager.requestLocationUpdates(
                provider, 
                MINIMUM_TIME_BETWEEN_UPDATES, 
                MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
                this
        );
    }

    /* Remove the locationlistener updates when Activity is paused */
    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        float lat = (float) (location.getLatitude());
        float lng = (float) (location.getLongitude());
        longitudeField.setText(String.valueOf(lng));
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "Enabled new provider " + provider,
                Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "Disenabled provider " + provider,
                Toast.LENGTH_SHORT).show();

    }
    protected void Display(Cursor c) {
        Toast.makeText(this, "rowid: " + c.getString(0) + "\n" +
         "Latitude: " + c.getString(1) + "\n" + "Longitude: " + c.getString(2) + "\n" +
         Toast.LENGTH_LONG, 0).show();    
    }

    **updata Logcat Error Message**



   "01-06 12:08:27.376: ERROR/AndroidRuntime(9725): java.lang.RuntimeException: Unable to resume activity {com.varma.samples.conntest/com.varma.samples.conntest.MainActivity}: java.lang.NullPointerException
    01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at  android.app.ActivityThread.performResumeActivity(ActivityThread.java:3133)
    01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3148)
    01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2689)
    01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at android.app.ActivityThread.access$2300(ActivityThread.java:126)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2038)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at android.os.Handler.dispatchMessage(Handler.java:99)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at android.os.Looper.loop(Looper.java:123)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at android.app.ActivityThread.main(ActivityThread.java:4632)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at java.lang.reflect.Method.invokeNative(Native Method)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at java.lang.reflect.Method.invoke(Method.java:521)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:871)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at dalvik.system.NativeStart.main(Native Method)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725): Caused by: java.lang.NullPointerException
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at com.varma.samples.conntest.MainActivity.onResume(MainActivity.java:158)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1149)
    01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at android.app.Activity.performResume(Activity.java:3823)
  01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3123)
"

我的清单文件*更新*

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.varma.samples.conntest"
  android:versionCode="1"
  android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".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>

</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
      <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
 <uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />     </manifest>

Hai am new in android Application,am trying to get the latitude and longtitude using Broadcast receiver.But my Application is Getting force Close.I dont know why it happens.Anybody kindly rectify my error.

        @Override
        public void onClick(View v) 
        {
             locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
             // Define the criteria how to select the locatioin provider -> use
             // default
             Criteria criteria = new Criteria();

         provider = locationManager.getBestProvider(criteria, false);
         Location location = locationManager.getLastKnownLocation(provider);

         // Initialize the location fields
         if (location != null) {
            System.out.println("Provider " + provider + " has been selected.");
            float lat = (float) (location.getLatitude());
            float lng = (float) (location.getLongitude());
            latituteField.setText(String.valueOf(lat));
            longitudeField.setText(String.valueOf(lng));

         } else {
            latituteField.setText("provider not available");
            longitudeField.setText("provider not available");
         }
            registerReceiver(receiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
        }
    });

        private class ConnectivityReceiver extends BroadcastReceiver{

            @Override
            public void onReceive(Context context, Intent intent) {
                    NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

                    if(null != info)
                    {
                            String state = getNetworkStateString(info.getState());
                            String stateString = info.toString().replace(',', '\n');
                            if(state.equals("Connected")){
                                result();

                            }

                    }
            }

}
    @Override
    protected void onResume() {
        super.onResume();
        //locationManager.requestLocationUpdates(provider,1000, 1, this);
        locationManager.requestLocationUpdates(
                provider, 
                MINIMUM_TIME_BETWEEN_UPDATES, 
                MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
                this
        );
    }

    /* Remove the locationlistener updates when Activity is paused */
    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        float lat = (float) (location.getLatitude());
        float lng = (float) (location.getLongitude());
        longitudeField.setText(String.valueOf(lng));
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "Enabled new provider " + provider,
                Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "Disenabled provider " + provider,
                Toast.LENGTH_SHORT).show();

    }
    protected void Display(Cursor c) {
        Toast.makeText(this, "rowid: " + c.getString(0) + "\n" +
         "Latitude: " + c.getString(1) + "\n" + "Longitude: " + c.getString(2) + "\n" +
         Toast.LENGTH_LONG, 0).show();    
    }

    **updata Logcat Error Message**



   "01-06 12:08:27.376: ERROR/AndroidRuntime(9725): java.lang.RuntimeException: Unable to resume activity {com.varma.samples.conntest/com.varma.samples.conntest.MainActivity}: java.lang.NullPointerException
    01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at  android.app.ActivityThread.performResumeActivity(ActivityThread.java:3133)
    01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3148)
    01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2689)
    01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at android.app.ActivityThread.access$2300(ActivityThread.java:126)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2038)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at android.os.Handler.dispatchMessage(Handler.java:99)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at android.os.Looper.loop(Looper.java:123)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at android.app.ActivityThread.main(ActivityThread.java:4632)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at java.lang.reflect.Method.invokeNative(Native Method)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at java.lang.reflect.Method.invoke(Method.java:521)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:871)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at dalvik.system.NativeStart.main(Native Method)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725): Caused by: java.lang.NullPointerException
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at com.varma.samples.conntest.MainActivity.onResume(MainActivity.java:158)
     01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1149)
    01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at android.app.Activity.performResume(Activity.java:3823)
  01-06 12:08:27.376: ERROR/AndroidRuntime(9725):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3123)
"

my manifestfile*update*

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.varma.samples.conntest"
  android:versionCode="1"
  android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".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>

</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
      <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
 <uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />     </manifest>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

瀞厅☆埖开 2025-01-01 22:24:45

移动线

位置管理器 = (位置管理器)
getSystemService(Context.LOCATION_SERVICE);

从onclick方法到oncreate方法

Move the line

locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);

from onclick method to oncreate method

夏日浅笑〃 2025-01-01 22:24:45

在清单中注册广播接收器。请参阅

Register the broadcast Receiver in your manifest. refer this

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文