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

Android 如果调用requestLocationUpdates获取用户的新位置,应用程序将崩溃,android,gps,xamarin.android,Android,Gps,Xamarin.android,我正在使用MonoDroid平台开发android应用程序。此应用程序中有两个模块,一个是驾驶员模块,另一个是乘客模块。当乘客预订出租车时,他/她将能够在地图上查看出租车的位置 在驱动程序模块中,我实现了两个类,一个是GPSTracker类,另一个是NorthStarBackgroundService类。(下面给出了这两个类的代码) NorthStarBackgroundService上名为UpdatePosition的方法负责更新数据库中的驾驶员位置,乘客模块从中获取坐标并在地图中显示驾驶员位

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

在驱动程序模块中,我实现了两个类,一个是GPSTracker类,另一个是NorthStarBackgroundService类。(下面给出了这两个类的代码)

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

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

可能熟悉单机器人环境的人,请帮我解决这个问题。这是5天,我试图解决这个问题,但我不能做到这一点

我使用网络提供商只是为了获得粗略的位置。我将扩展到全球定位系统供应商,如果这一个完美的工作

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


    }
}
NorthstarBrackRoundService代码

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
I/EXC_logstart(306):****************启动驱动模块****************
I/ActivityManager(60):显示的活动MyDriver\u Driver.MyDriver\u Driver/northstar.Driver.Activity1:6632毫秒(总计6632毫秒)
D/dalvikvm(128):GC_显式释放了201个对象/9848字节(188ms)
D/dalvikvm(120):GC_EXTERNAL_ALLOC在144ms内释放3163个对象/207880字节
D/dalvikvm(120):GC_EXTERNAL_ALLOC在172ms内释放935个对象/60072字节
W/KeyCharacterMap(306):没有id为0的键盘
W/KeyCharacterMap(306):使用默认keymap:/system/usr/keychars/qwerty.kcm.bin
I/ARMAssembler(60):在8041202纳秒的[0x3bce60:0x3bcf1c]处生成扫描线\uuU00000077:03515104\uU00000000\uU00000000[33 ipp](47英寸)
I/ActivityManager(60):启动活动:Intent{cmp=MyDriver\u Driver.MyDriver\u Driver/northstar.Driver.MainActivity(具有附加功能)}
I/ActivityManager(60):显示的活动MyDriver\u Driver.MyDriver\u Driver/northstar.Driver.Main活动:1216毫秒(总计1216毫秒)
E/mono(306):
E/mono(306):引发了未处理的异常:Java.Lang.NullPointerException:类型为“Java.Lang.NullPointerException”的异常。
E/mono(306):在Android.Runtime.JNIEnv.CallNonvirtualObjectMethod(IntPtr jobject,IntPtr jclass,IntPtr jmethod,Android.Runtime.JValue[]parms)[0x00000]in:0
E/mono(306):位于Android.Content.ContextWrapper.GetSystemService(System.String名称)[0x00000]中:0
E/mono(306):位于NorthStar.Driver.GPSTracker.getLocation()[0x00000]中:0
E/mono(306):位于NorthStar.Driver.GPSTracker..ctor(Android.Content.Context)[0x00000]中:0
E/mono(306):位于NorthStar.Driver.MainActivity.RequestWork()[0x00000]中:0
E/mono(306):在NorthStar.Driver.MainActivity.b_u 2(System.Object x)[0x00000]中:0
E/mono(306):--托管异常堆栈跟踪结束---
E/mono(306):java.lang.NullPointerException
E/mono(306):位于android.content.ContextWrapper.getSystemService(ContextWrapper.java:363)
E/mono(306):在dalvik.system.NativeStart.run(本机方法)
E/mono(306):
D/合子(33):进程306干净地退出(255)
I/ActivityManager(60):进程MyDriver\u Driver.MyDriver\u Driver(pid 306)已死亡。
I/WindowManager(60):赢得死亡:窗口{45103638 MyDriver\u Driver.MyDriver\u Driver/northstar.Driver.Activity1暂停=false}
I/WindowManager(60):赢得死亡:窗口{4511aac0 MyDriver\u Driver.MyDriver\u Driver/northstar.Driver.main活动暂停=false}
W/ActivityManager(60):计划在5000ms内重新启动崩溃的服务MyDriver\u Driver.MyDriver\u Driver/northstar.Driver.NorthStarBackgroundService
I/ActivityManager(60):启动过程MyDriver\u Driver.MyDriver\u活动的驱动程序MyDriver\u Driver.MyDriver\u Driver/northstar.Driver.Activity1:pid=320 uid=10042 gids={30031015}
I/UsageStats(60):MyDriver\u Driver.MyDriver\u Driver的意外恢复,但已在MyDriver\u Driver.MyDriver\u Driver中恢复
I/ActivityThread(320):发布提供程序MyDriver\u Driver.MyDriver\u Driver.\uuuu mono\u init\uuuuu:mono.mono运行时提供程序
D/dalvikvm(320):尝试加载lib/data/data/MyDriver\u Driver.MyDriver\u Driver/lib/libmonodroid.so 0x44edf660
D/dalvikvm(320):添加了共享lib/data/data/MyDriver\u Driver.MyDriver\u Driver/lib/libmonodroid.so 0x44edf660
E/mono(320):警告:此应用程序支持的运行时版本不可用。
E/mono(320):使用默认运行时:v2.0.50727
I/monodroid gc(320):环境支持jni NewWeakGlobalRef
W/单机器人gc(320):GREF gc阈值:1800
I/EXCèU logstart(320):******************启动驱动器模块****************
W/InputManagerService(60):获取远程异常,向pid 306 uid 10042发送setActive(false)通知
I/ActivityManager(60):显示的活动MyDriver\u Driver.MyDriver\u Driver/northstar.Driver.Activity1:4214毫秒(总计4214毫秒)
I/MonoDroid(320):未处理的异常:System.NullReferenceException:对象引用未设置为对象的实例
I/MonoDroid(320):位于NorthStar.Driver.NorthStarBackgroundService.OnStart(一个
_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
}