Android 在MonoDroid中创建用户会话

Android 在MonoDroid中创建用户会话,android,session,xamarin.android,Android,Session,Xamarin.android,我正在开发和android应用程序,需要用户登录。我正在使用Monodroid开发这个应用程序。在我的应用程序中,用户登录时将启动一系列活动。我已经将登录活动设置为主启动器,当用户成功登录时,用户将被发送到主活动 我想知道如何为用户保存会话,以便用户不需要在每次启动应用程序时登录 由于单机器人对我来说很陌生,我无法让它工作。人们建议我使用SharedPrevencs来创建会话,但为了让它正常工作,应用程序总是崩溃。 当用户处于mainactivity时,崩溃的原因是用户的空值。根据许多用户的建议

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

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

由于单机器人对我来说很陌生,我无法让它工作。人们建议我使用SharedPrevencs来创建会话,但为了让它正常工作,应用程序总是崩溃。 当用户处于mainactivity时,崩溃的原因是用户的空值。根据许多用户的建议,我将主活动创建为Main laucher,并检查用户是否从那里登录。但对我来说什么都不管用

我已经包括了登录活动和主要活动的全部代码。我想将“driverId”保存在prefrence中,当任何应用程序重新启动时,主活动都将从prefrence中检索“driverId”

请一些熟悉单机器人环境的人帮我解决这个问题

登录活动代码

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));
            };
        }
    }
}
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; }
    }
}
使用系统;
使用Android.App;
使用Android.Content;
使用Android.Runtime;
使用Android.Views;
使用Android.Widget;
使用Android.OS;
使用Android.Locations;
使用RestSharp;
使用northstar.Api.Requests;
使用northstar.Api.Results;
使用NorthStar.Driver.Application;
使用Android.Preferences;
使用Object=Java.Lang.Object;
名称空间NorthStar.Driver
{
公共类DriverLogonAsync:AsyncTask
{
私有进程对话框;
私有语境m_语境;
私家车Logon m_司机;
私有布尔(bool)restererror ;;
公共DriverLogonAsync(上下文上下文,DriverLogon驱动程序)
{
m_context=上下文;
m_driver=驱动程序;
_resterror=false;
}
/*
*投掷
*应该分离出逻辑并使用MyMessagebox。。
*/
私有void SetComfirmAlertBox(字符串carNum、DriverLogonResult结果)
{
var api=newconnecttosever(Helper.GetServer(m_上下文));
字符串resultOfCarDetail;CarDetails res;
尝试
{
resultOfCarDetail=api.ComfirmLogginOn(m_驱动程序);
}
抓住
{
Android.Util.Log.Info(“EXC_conflogon1”,“确认登录失败”);
投掷;
}
尝试
{
res=Newtonsoft.Json.JsonConvert.DeserializeObject(resultOfCarDetail);
}
捕获(例外情况除外)
{
Android.Util.Log.Info(“EXC_conflogon2”,“反序列化确认登录失败\n”+ex.Message);
投掷;
}
if(res.carExists!=真)
{
设置AlertBox(“Opps!!!!!!!”,“此车号错误!!!!”,“确定”,m_上下文);
}
其他的
{
字符串carType=res.carType;
字符串seatNum=res.numfseats.ToString();
//MainActivity act=新的MainActivity(result.driverId);
var mact=新意图(m_上下文,类型(主要活动));
mact.PutExtra(“driverID”,result.driverID.ToString());
MyMessageBox.SetAlertBox(“Comfirm!”,“您的汽车是:“+carType+”和“+seatNum+”座椅??”、“是”、“否”、mact、m_上下文);
}
}
/*私有void changerdriverstatues()
{
}*/
受保护的覆盖无效OnPreExecute()
{
base.OnPreExecute();
processDialog=ProgressDialog.Show(m_上下文,“驱动程序登录…”,“请稍候…”,true,true);
}
受保护的覆盖对象DoInBackground(params对象[]@params)
{
var api=newconnecttosever(Helper.GetServer(m_上下文));
string res=string.Empty;
尝试
{
res=api.DriverLogingOn(m_-driver);
}
抓住
{
_resterror=true;
Android.Util.Log.Info(“EXC_dlogon1”,“驱动程序登录失败”);
返回-1;
}
返回res;
}
受保护的重写无效OnPostExecute(对象结果)
{
base.OnPostExecute(结果);
//隐藏并终止进度对话框
processDialog.Hide();
processDialog.Cancel();
如果(_resterror==true)
{
Android.Util.Log.Info(“EXC_dlogon2”,“登录连接失败,noop”);
返回;
}
DriverLogonResult resDriverDetail;
尝试
{
resDriverDetail=Newtonsoft.Json.JsonConvert.DeserializeObject(result.ToString());
}
捕获(例外情况除外)
{
Android.Util.Log.Info(“EXC_dlogon3”,“登录请求失败,noop\n”+ex.Message);
返回;
}
if(resDriverDetail.logonSuccess)
{
此.SetComfirmAlertBox(m_driver.carNum,resDriverDetail);
}
其他的
{
SetAlertBox(“错误!”,“错误的用户名或密码!!!”,“确定!”,m_上下文);
}
}
}
[活动(Label=“MyDriver Driver”,MainLauncher=true,Icon=“@drawable/Icon”,NoHistory=true)]
公共课堂活动1:活动
{
私有void CreateAlert()
{
AlertDialog.Builder=新建AlertDialog.Builder(此);
builder.SetTitle(“GPS关闭”)
.SetMessage(“您需要GPS来连接此应用程序。”+“\n”+
“是否要转到“设置”菜单?”)
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);