2

我正在开发需要用户登录的 android 应用程序。我正在使用 Monodroid 开发这个应用程序。在我的应用程序中,用户登录时将启动许多活动。我已将登录活动设置为主启动器,当用户成功登录时,用户将被发送到主活动。

我想如何为用户保存会话,以便用户每次启动应用程序时都不需要登录。

由于 monodroid 对我来说很新,我无法完成这项工作。人们推荐我使用 SharedPrefrencs 来创建会话,但尝试了很多让它工作,应用程序总是崩溃。当用户处于 mainactivity 时,崩溃的原因是用户的 null 值。正如许多用户所推荐的那样,我将 Main Activity 创建为 main laucher 并检查用户是否从那里登录。但没有什么对我有用。

我已经包含了登录活动和主活动的整个代码。我想将“driverId”保存在首选项中,并且当重新启动应用程序时,主要活动将从首选项中检索“driverId”。

请一些熟悉 monodroid 环境的人可以帮助我解决这个问题。

登录活动代码

using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Locations;
using RestSharp;
using TheNorthStar.Api.Requests;
using TheNorthStar.Api.Results;
using NorthStar.Driver.Application;
using Android.Preferences;
using Object = Java.Lang.Object;


namespace NorthStar.Driver
{
    public class DriverLogonAsync : AsyncTask

    {
        private ProgressDialog processDialog;
        private Context m_context;
        private DriverLogon m_driver;

        private bool _resterror;

        public DriverLogonAsync( Context context, DriverLogon driver )
        {
            m_context = context;
            m_driver = driver;

            _resterror = false;
        }

        /*
         * throws
         * should separate out logic and use MyMessagebox..
         */
        private void SetComfirmAlertBox(string carNum, DriverLogonResult result)
        {
            var api = new ConnectToSever(Helper.GetServer(m_context));
            string resultOfCarDetail; CarDetails res;
            try
            {
                resultOfCarDetail = api.ComfirmLogginOn(m_driver);
            }
            catch
            {
                Android.Util.Log.Info("EXC_conflogon1", "confirm logging on failed");
                throw;
            }
            try
            {
                res = Newtonsoft.Json.JsonConvert.DeserializeObject<CarDetails>(resultOfCarDetail);
            }
            catch (Exception ex)
            {
                Android.Util.Log.Info("EXC_conflogon2", "deserialize confirm logging on failed\n" + ex.Message);
                throw;
            }

            if (res.carExists != true)
            {
                MyMessageBox.SetAlertBox("Opps!!!!!!!!", "This Car Number Was Wrong!!!!", "OK", m_context);
            }
            else
            {
                string carType = res.carType;
                string seatNum = res.numOfSeats.ToString();
               // MainActivity act = new MainActivity( result.driverId );
                var mact = new Intent(m_context,typeof(MainActivity) );
                mact.PutExtra( "driverID",  result.driverId.ToString() );
                MyMessageBox.SetAlertBox("Comfirm!", "Your car is a: " + carType + " with " + seatNum + " seats??", "Yes", "No", mact,m_context);


            }
        }

        /*private void ChangeDriverStatues()
        {

        }*/

        protected override void OnPreExecute()
        {
            base.OnPreExecute();
            processDialog = ProgressDialog.Show( m_context, "Driver Loging On...", "Please Wait...", true, true);
        }



        protected override Object DoInBackground(params Object[] @params)
        {
            var api = new ConnectToSever(Helper.GetServer(m_context));

            string res = string.Empty;
            try
            {
                res = api.DriverLogingOn(m_driver);
            }
            catch
            {
                _resterror = true;
                Android.Util.Log.Info("EXC_dlogon1", "driver logon failed");
                return -1;
            }
            return res;
        }

        protected override void OnPostExecute(Object result)
        {
            base.OnPostExecute(result);
            //hide and kill the progress dialog
            processDialog.Hide();
            processDialog.Cancel();

            if (_resterror == true)
            {
                Android.Util.Log.Info("EXC_dlogon2", "logon connection has failed, noop");
                return;
            }

            DriverLogonResult resDriverDetail;
            try
            {
                resDriverDetail = Newtonsoft.Json.JsonConvert.DeserializeObject<DriverLogonResult>(result.ToString());
            }
            catch (Exception ex)
            {
                Android.Util.Log.Info("EXC_dlogon3", "logon deser has failed, noop\n" + ex.Message);
                return;
            }

            if (resDriverDetail.logonSuccess)
            {
                this.SetComfirmAlertBox( m_driver.carNum, resDriverDetail );  
            }
            else
            {
                MyMessageBox.SetAlertBox("Wrong!", "Wrong username or password!!!", "OK!",m_context);
            }
        }
    }

    [Activity(Label = "MyDriver-Driver", MainLauncher = true, Icon = "@drawable/icon", NoHistory = true)]
    public class Activity1 : Activity
    {
        private void CreateAlert()
        {

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.SetTitle("GPS is Off")
                .SetMessage("You need GPS to you this application."+ "\n" +
                             "Do you want to go to settings menu?")
                .SetPositiveButton("Setting",
                    (sender, e) =>
                    {
                        Intent intent = new Intent(Android.Provider.Settings.ActionLocationSourceSettings);
                        StartActivity(intent);
                        this.Finish();
                    })
                    .SetNegativeButton("No", (sender, e) => this.Finish());

            AlertDialog alert = builder.Create();
            alert.Show();
        }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            Android.Util.Log.Info("EXC_logstart", "**************** starting driver module ****************");

            Boolean isGPSEnabled = false;
            Boolean isNetworkEnabled = false;
            LocationManager _locationManager;
            _locationManager = (LocationManager)GetSystemService(LocationService);
            isGPSEnabled = _locationManager.IsProviderEnabled(LocationManager.GpsProvider);

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

            if (!isGPSEnabled && !isNetworkEnabled)
            {
                CreateAlert();
            }

            // Get our button from the layout resource,
            // and attach an event to it
            EditText eTextUsername = FindViewById<EditText>(Resource.Id.UserNameBox);
            EditText eTextPassword = FindViewById<EditText>(Resource.Id.PasswordBox);
            EditText eTextCarNum = FindViewById<EditText>(Resource.Id.CarNumBox);
            Button viewPrefsBtn = FindViewById<Button>(Resource.Id.BtnViewPrefs);
            Button button = FindViewById<Button>(Resource.Id.MyButton);

            button.Click += delegate 
            {
                if (eTextCarNum.Text != "" && eTextPassword.Text != "" && eTextUsername.Text != "")
                {
                    DriverLogon driver = new DriverLogon();
                    driver.userName = eTextUsername.Text;
                    driver.password = eTextPassword.Text;
                    driver.carNum = eTextCarNum.Text;
                    DriverLogonAsync asyDriver = new DriverLogonAsync(this, driver);
                    asyDriver.Execute();
                }
            };

            viewPrefsBtn.Click += (sender, e) =>
            {
                StartActivity(typeof(PreferencesActivity));
            };
        }
    }
}

因此,当用户成功登录时,“driverId”应该被保存,并且可以在重新启动应用程序时从主要活动中检索。

主要活动代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Android.Preferences;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using RestSharp;
using Android.Locations;
using TheNorthStar.Api.Requests;
using TheNorthStar.Api.Results;
using NorthStar.Driver.Application;
using System.Timers;
using AutoMapper;
using Object = Java.Lang.Object;
using Timer = System.Timers.Timer;


namespace NorthStar.Driver
{
    [Activity(Label = "Home")]
    public class MainActivity : Activity
    {   
        string m_driverId;
        string m_bookingId;
        string m_address;
        int i = 1;
        private Timer _requestWorkTimer;

        /*
         * throws
         */
        private void SetDriverStatues(string status)
        {
            m_driverId = Intent.GetStringExtra("driverID");
            var api = new ConnectToSever(Helper.GetServer(ApplicationContext));
            DriverLogon driver = new DriverLogon();
            //Booking booking = RequestToSever();
            driver.driverID = Int32.Parse(m_driverId);
            driver.driverStatus = status;
            try
            {
                api.SetDriverStatus(driver);
            }
            catch
            {
                Android.Util.Log.Info("EXC_setdstat1", "set driver status failed");
                throw;
            }
        }

        protected override void OnDestroy()
        {
            base.OnDestroy();
            _requestWorkTimer.Stop();
        }

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Mainpage);
            //EditText messageBox = FindViewById<EditText>( Resource.Id.MessagesBox );
            Button button = FindViewById<Button>(Resource.Id.LogOutButton);

            m_driverId = Intent.GetStringExtra("driverID");
            var service = new Intent(this, typeof(NorthStarBackgroundService));
            service.PutExtra("driverId",m_driverId);

            StartService(service);


            ThreadPool.QueueUserWorkItem(state => SetDriverStatues("Available"));
           // this.SetDriverStatues( "Available" );

            _requestWorkTimer = new Timer(15000);
            _requestWorkTimer.Elapsed += (sender, e) =>
            {
                ThreadPool.QueueUserWorkItem(x => RequestWork());
            };
            _requestWorkTimer.Start();

            button.Click += (sender, args) =>
                                {
                                    try
                                    {
                                        SetDriverStatues("Logoff");
                                    }
                                    catch
                                    {
                                        Android.Util.Log.Info("EXC_setdstat2", "set driver status failed");
                                        return;
                                    }
                                    var mact = new Intent(this, typeof(Activity1));
                                    mact.AddFlags(ActivityFlags.ClearTop);
                                    StartActivity(mact);
                                };
        }

        private void CheckMessage()
        {
          /*  if (  )
            {
                //timeout so return home

            }
           /* else
            {
                timerCount--;
                RunOnUiThread(() => { jobTimerLabel.Text = string.Format("{0} seconds to respond", timerCount); });

            }*/
        }

        protected override void OnResume()
        {
            base.OnResume();
            _requestWorkTimer.Start();
        }

        private void CreateAlert()
        {

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.SetTitle("GPS is Off")
                .SetMessage("Do you want to go to settings menu?")
                .SetPositiveButton("Setting",
                    (sender, e) =>
                    {
                        Intent intent = new Intent(Android.Provider.Settings.ActionLocationSourceSettings);
                        StartActivity(intent);
                        this.Finish();
                    })
                    .SetNegativeButton("No", (sender, e) => this.Finish());

            AlertDialog alert = builder.Create();
            alert.Show();
        }

        /*
         * throws
         */
        private void RequestWork()
        {
            _requestWorkTimer.Stop();
            var api = new ConnectToSever(Helper.GetServer(ApplicationContext));
            DriverMoreWorkRequest driver = new DriverMoreWorkRequest();
            driver.driverID = Int32.Parse(m_driverId);
            NorthStarBackgroundService n = new NorthStarBackgroundService();
            driver.Lat = n.currentLattitude;
            driver.Lng = n.currentLongtitude;
            Object result; Booking booking;
            try
            {
                result = api.RequestWork(driver);
            }
            catch
            {
                Android.Util.Log.Info("EXC_reqwork1", "request work failed");
                throw;
            }
            try
            {
                booking = Newtonsoft.Json.JsonConvert.DeserializeObject<Booking>(result.ToString());
            }
            catch (Exception ex)
            {
                Android.Util.Log.Info("EXC_reqwork1", "deserialize request work failed\n" + ex.Message);
                throw;
            }
            if (booking != null)
            {
                m_bookingId = booking.BookingId.ToString();
                //string add = api.GetCustomerAddress(booking);

                RunOnUiThread(() =>
                {
                    var mact = new Intent(this, typeof(NewWorkAvailableActivity));
                    mact.PutExtra("driverID", m_driverId);
                    mact.PutExtra("bookingId", m_bookingId);
                    mact.PutExtra("fullAddress", booking.Address);
                    mact.PutExtra("jobLocation", booking.PickupSuburb);
                    mact.PutExtra("customerPhoneNumber", booking.PassengerPhoneNumber);

                    StartActivity(mact);

                });
            }
            else
            {
                _requestWorkTimer.Start();
            }                     
        }

        public object even { get; set; }
    }
}
4

1 回答 1

0

我完全确定您在这里尝试做什么,但要从 Shared Preferences 尝试获取驱动程序 ID(来自登录活动):

var prefs = GetSharedPreferences("MyApp",Android.Content.FileCreationMode.Private);
var driverID = 0;
if (prefs.Contains("DriverID"))
{
    driverID = prefs.GetInt("DriverID", 0);
}
else
{
    //Call the Async Task to get the Driver or whatever and when you've got it:
    var prefsEdit = prefs.Edit();
    prefsEdit.PutInt("DriverID", driver.ID);
    prefsEdit.Commit();
    driverID = prefs.GetInt("DriverID", 0);
}

var mact = new Intent(this, typeof(MainActivity))
            .PutExtra("driverID", driverID);
StartActivity(mact);

或者,我会将整个 Driver 对象粘贴在 sqlite db 中,并在您每次进入时将其取回,但显然我不知道您的要求。

于 2012-10-22T15:51:10.887 回答