我正在开发和Android应用程序,需要用户登录。我正在使用Monodroid开发此应用程序。在我的应用程序中,有许多活动将在用户登录时启动。我已将Login Activity设置为主启动器,当用户成功登录时,用户将被发送到主活动。
我有些想要为用户保存会话,以便用户每次启动应用程序时都不需要登录。
由于monodroid对我来说很新,我无法做到这一点。人们建议我使用SharedPrefrencs创建会话,但尝试了很多工作,应用程序总是崩溃。 当用户处于主要活动状态时,崩溃的原因是用户的空值。根据许多用户的建议,我创建主要活动作为主要的laucher并检查用户是否从那里登录。但没有什么对我有用。
我已将我的整个代码包含在Login Activity和Main Activity中。我想在prefrences中保存“driverId”,当应用程序被重新启动时,主要活动将从prefrences中检索“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; }
}
}
答案 0 :(得分:0)
我确定你要在这里尝试做什么但是要从共享偏好设置中获取驱动程序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数据库中并在每次进入时将其取回,但显然我不知道你的要求。