如果调用requestLocationUpdates以获取用户的新位置,则应用程序崩溃

时间:2012-10-06 18:33:38

标签: android gps xamarin.android

我正在使用MonoDroid平台开发Android应用程序。该应用程序中有两个模块,一个是驱动程序模块,另一个是乘客模块。每当乘客预订出租车时,他/她将能够在地图上查看出租车的位置。

在驱动程序模块中,我实现了两个类,一个是GPSTracker类,另一个是NorthStarBackgroundService类。(CODE GIVEN BELOW FOR BOTH)。

NorthStarBackgroundService上名为UpdatePosition的方法负责更新乘客模块获取坐标的数据库中的驾驶员位置,并在地图中显示驾驶员位置。方法UpdatePosition从实现ILocationListener的GPSTracker类获取驱动程序的坐标。

正如您在代码中看到的,我已注释掉RequestLocationUpdates。每当我运行应用程序而不注释掉那行代码时,我的应用程序崩溃了。但是当我用注释运行它时它不会崩溃。我不知道这个问题。此外,当驾驶员移动时,该位置不会更新。

可能熟悉单声道环境的人,请帮我解决这个问题。我试图解决这个问题已经5天了,但我无法做到。

我只使用网络提供商来获取粗略的位置。如果这个工作完美,我将扩展到Gps提供商。

GPSTracker代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Locations;
using Java.IO;

namespace NorthStar.Driver
{
    public class GPSTracker : Service, ILocationListener

    {

        public readonly Context mContext;

       // flag for network status
        Boolean isNetworkEnabled = false;

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

        public LocationManager locationManager;



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

        }


        public Location getLocation()
        {
            locationManager = (LocationManager)mContext.GetSystemService(Context.LocationService);

            // getting network status
            isNetworkEnabled = locationManager.IsProviderEnabled(LocationManager.NetworkProvider);

            if (isNetworkEnabled)
            {
                // locationManager.RequestLocationUpdates(LocationManager.NetworkProvider, 1000, 10, this);

                if (locationManager != null)
                {
                    location = locationManager.GetLastKnownLocation(LocationManager.NetworkProvider);
                    if (location != null)
                    {
                        latitude = location.Latitude;
                        longitude = location.Longitude;
                    }
                }
            }

            return location;
        }


        /**
        * Function to get latitude
        * */
        public double getLatitude()
        {

            latitude = location.Latitude;
            // return latitude

            return latitude;
        }


        /**
         * Function to get longitude
         * */
        public double getLongitude()
        {
            latitude = location.Longitude;
            // return latitude

            return longitude;           
        }

        public void OnLocationChanged(Location location)
        {
        }


        public void OnProviderDisabled(String provider)
        {
        }


        public void OnProviderEnabled(String provider)
        {
        }


        public void OnStatusChanged(string provider, Availability status, Bundle extras)
        {
        }


        public override IBinder OnBind(Intent arg0)
        {
            return null;
        }


    }
}

NorthStarBrackgroundService的代码

UpdatePosition每20秒调用一次,因为已为此设置了计时器。 我创建了一个GPSTracker类的对象,并设置了发送到数据库的纬度和经度值。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Preferences;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using NorthStar.Driver.Application;
using TheNorthStar.Api.Requests;
using TheNorthStar.Api.Results;

namespace NorthStar.Driver
{
    [Service]
    public class NorthStarBackgroundService : Service
    {
        private string driverId;
        private System.Timers.Timer timer;

        public override IBinder OnBind(Intent intent)
        {
            return null;
        }

        public override void OnCreate()
        {
            base.OnCreate();
            timer = new System.Timers.Timer(20000);
            timer.Elapsed += TimerElapsed;              
        }

        void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            ThreadPool.QueueUserWorkItem(UpdatePosition);
        }

        public override void OnStart(Intent intent, int startId)
        {
            base.OnStart(intent, startId);

            driverId = intent.GetStringExtra("driverId");

            timer.Start();
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
            timer.Stop();
        }

        private void UpdatePosition(object data)
        {

            ConnectToSever api = new ConnectToSever(Helper.GetServer(ApplicationContext));

            GPSTracker gps = new GPSTracker(ApplicationContext);

            var pos = new DriverPosition() { Latitude = gps.latitude, Longitude = gps.longitude, DriverId = driverId };
            try
            {
                api.UpdatePosition(pos);
            }
            catch
            {
                Android.Util.Log.Info("EXC_update1", "update driver failed");
            }
        }
    }
}

我不知道哪个方面出错导致应用程序崩溃。 对此的任何暗示都将非常感激。

记录Cat输出

I/EXC_logstart(  306): **************** starting driver module ****************
I/ActivityManager(   60): Displayed activity MyDriver_Driver.MyDriver_Driver/northstar.driver.Activity1: 6632 ms (total 6632 ms)
D/dalvikvm(  128): GC_EXPLICIT freed 201 objects / 9848 bytes in 188ms
D/dalvikvm(  120): GC_EXTERNAL_ALLOC freed 3163 objects / 207880 bytes in 144ms
D/dalvikvm(  120): GC_EXTERNAL_ALLOC freed 935 objects / 60072 bytes in 172ms
W/KeyCharacterMap(  306): No keyboard for id 0
W/KeyCharacterMap(  306): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
I/ARMAssembler(   60): generated scanline__00000077:03515104_00000000_00000000 [ 33 ipp] (47 ins) at [0x3bce60:0x3bcf1c] in 8041202 ns
I/ActivityManager(   60): Starting activity: Intent { cmp=MyDriver_Driver.MyDriver_Driver/northstar.driver.MainActivity (has extras) }
I/ActivityManager(   60): Displayed activity MyDriver_Driver.MyDriver_Driver/northstar.driver.MainActivity: 1216 ms (total 1216 ms)
E/mono    (  306): 
E/mono    (  306): Unhandled Exception: Java.Lang.NullPointerException: Exception of type 'Java.Lang.NullPointerException' was thrown.
E/mono    (  306):   at Android.Runtime.JNIEnv.CallNonvirtualObjectMethod (IntPtr jobject, IntPtr jclass, IntPtr jmethod, Android.Runtime.JValue[] parms) [0x00000] in <filename unknown>:0 
E/mono    (  306):   at Android.Content.ContextWrapper.GetSystemService (System.String name) [0x00000] in <filename unknown>:0 
E/mono    (  306):   at NorthStar.Driver.GPSTracker.getLocation () [0x00000] in <filename unknown>:0 
E/mono    (  306):   at NorthStar.Driver.GPSTracker..ctor (Android.Content.Context context) [0x00000] in <filename unknown>:0 
E/mono    (  306):   at NorthStar.Driver.MainActivity.RequestWork () [0x00000] in <filename unknown>:0 
E/mono    (  306):   at NorthStar.Driver.MainActivity.<OnCreate>b__2 (System.Object x) [0x00000] in <filename unknown>:0 
E/mono    (  306):   --- End of managed exception stack trace ---
E/mono    (  306): java.lang.NullPointerException
E/mono    (  306):  at android.content.ContextWrapper.getSystemService(ContextWrapper.java:363)
E/mono    (  306):  at dalvik.system.NativeStart.run(Native Method)
E/mono    (  306): 
D/Zygote  (   33): Process 306 exited cleanly (255)
I/ActivityManager(   60): Process MyDriver_Driver.MyDriver_Driver (pid 306) has died.
I/WindowManager(   60): WIN DEATH: Window{45103638 MyDriver_Driver.MyDriver_Driver/northstar.driver.Activity1 paused=false}
I/WindowManager(   60): WIN DEATH: Window{4511aac0 MyDriver_Driver.MyDriver_Driver/northstar.driver.MainActivity paused=false}
W/ActivityManager(   60): Scheduling restart of crashed service MyDriver_Driver.MyDriver_Driver/northstar.driver.NorthStarBackgroundService in 5000ms
I/ActivityManager(   60): Start proc MyDriver_Driver.MyDriver_Driver for activity MyDriver_Driver.MyDriver_Driver/northstar.driver.Activity1: pid=320 uid=10042 gids={3003, 1015}
I/UsageStats(   60): Unexpected resume of MyDriver_Driver.MyDriver_Driver while already resumed in MyDriver_Driver.MyDriver_Driver
I/ActivityThread(  320): Publishing provider MyDriver_Driver.MyDriver_Driver.__mono_init__: mono.MonoRuntimeProvider
D/dalvikvm(  320): Trying to load lib /data/data/MyDriver_Driver.MyDriver_Driver/lib/libmonodroid.so 0x44edf660
D/dalvikvm(  320): Added shared lib /data/data/MyDriver_Driver.MyDriver_Driver/lib/libmonodroid.so 0x44edf660
E/mono    (  320): WARNING: The runtime version supported by this application is unavailable.
E/mono    (  320): Using default runtime: v2.0.50727
I/monodroid-gc(  320): environment supports jni NewWeakGlobalRef
W/monodroid-gc(  320): GREF GC Threshold: 1800
I/EXC_logstart(  320): **************** starting driver module ****************
W/InputManagerService(   60): Got RemoteException sending setActive(false) notification to pid 306 uid 10042
I/ActivityManager(   60): Displayed activity MyDriver_Driver.MyDriver_Driver/northstar.driver.Activity1: 4214 ms (total 4214 ms)
I/MonoDroid(  320): UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object
I/MonoDroid(  320): at NorthStar.Driver.NorthStarBackgroundService.OnStart (Android.Content.Intent,int) <0x00038>
I/MonoDroid(  320): at Android.App.Service.n_OnStart_Landroid_content_Intent_I (intptr,intptr,intptr,int) <0x00067>
I/MonoDroid(  320): at (wrapper dynamic-method) object.0333e05f-221e-4109-91bd-6a13aa2251bd (intptr,intptr,intptr,int) <0x0003b>
E/mono    (  320): 
E/mono    (  320): Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object
E/mono    (  320):   at NorthStar.Driver.NorthStarBackgroundService.OnStart (Android.Content.Intent intent, Int32 startId) [0x00000] in <filename unknown>:0 
E/mono    (  320):   at Android.App.Service.n_OnStart_Landroid_content_Intent_I (IntPtr jnienv, IntPtr native__this, IntPtr native_intent, Int32 startId) [0x00000] in <filename unknown>:0 
E/mono    (  320):   at (wrapper dynamic-method) object:0333e05f-221e-4109-91bd-6a13aa2251bd (intptr,intptr,intptr,int)
D/Zygote  (   33): Process 320 exited cleanly (1)
I/ActivityManager(   60): Process MyDriver_Driver.MyDriver_Driver (pid 320) has died.
W/ActivityManager(   60): Scheduling restart of crashed service MyDriver_Driver.MyDriver_Driver/northstar.driver.NorthStarBackgroundService in 20000ms
I/WindowManager(   60): WIN DEATH: Window{45127238 MyDriver_Driver.MyDriver_Driver/northstar.driver.Activity1 paused=false}
I/UsageStats(   60): Unexpected resume of com.android.launcher while already resumed in MyDriver_Driver.MyDriver_Driver
W/InputManagerService(   60): Got RemoteException sending setActive(false) notification to pid 320 uid 10042
I/ActivityManager(   60): Start proc MyDriver_Driver.MyDriver_Driver for service MyDriver_Driver.MyDriver_Driver/northstar.driver.NorthStarBackgroundService: pid=327 uid=10042 gids={3003, 1015}
I/ActivityThread(  327): Publishing provider MyDriver_Driver.MyDriver_Driver.__mono_init__: mono.MonoRuntimeProvider
D/dalvikvm(  327): Trying to load lib /data/data/MyDriver_Driver.MyDriver_Driver/lib/libmonodroid.so 0x44edf580
D/dalvikvm(  327): Added shared lib /data/data/MyDriver_Driver.MyDriver_Driver/lib/libmonodroid.so 0x44edf580
E/mono    (  327): WARNING: The runtime version supported by this application is unavailable.
E/mono    (  327): Using default runtime: v2.0.50727
I/monodroid-gc(  327): environment supports jni NewWeakGlobalRef
W/monodroid-gc(  327): GREF GC Threshold: 1800

2 个答案:

答案 0 :(得分:1)

我认为你以错误的方式解决这个问题。

发生了什么,您是否每次想要一个位置时实例化一个新的GPSTracker,然后尝试检索碰巧为空的位置的属性。

相反,我会直接在 NorthStarBackgroundService 中实现 ILocationListener

Greg Shackles&#39;这样一个听众here的例子就应该有你所需要的一切。

具体来说,获取最后一个已知位置并请求更新,如示例所示:

_locationManager = (LocationManager)GetSystemService(LocationService);
Location lastKnownLocation = _locationManager.GetLastKnownLocation(bestProvider);

if (lastKnownLocation != null) ... // Set your instance variable for location.

// You can set the thresholds that suit you here.
_locationManager.RequestLocationUpdates(bestProvider, 5000, 2, this);

然后执行:

public void OnLocationChanged(Location location)
{
    // Update your instance variable for location
}

在此之后你可以让 UpdatePosition()使用在 OnLocationChanged()中写入的位置。

答案 1 :(得分:0)

从堆栈跟踪看起来OnStart()中存在NullReferenceException。

我不熟悉服务 - 但可能是Intent为空 - 当然this reference说:

  

提供给startService(Intent)的Intent,如给定的那样。这可能是   如果服务在其进程消失后重新启动,则返回null   离开了,之前它还没有返回任何东西   START_STICKY_COMPATIBILITY。