ユーザーにログインが必要なAndroidアプリケーションを開発しています。このアプリケーションの開発には Monodroid を使用しています。私のアプリケーションには、ユーザーがログインすると開始される一連のアクティビティがあります。ログイン アクティビティをメイン ランチャーとして設定しました。ユーザーが正常にログインすると、ユーザーはメイン アクティビティに送られます。
ユーザーがアプリケーションを起動するたびにログインする必要がないように、ユーザーのセッションを保存する方法があります。
モノドロイドは私にとって非常に新しいので、私はそれを機能させることができません。人々はセッションを作成するために SharedPrerefrencs を使用することを勧めましたが、それを機能させるために多くのことを試みましたが、アプリケーションは常にクラッシュしました。クラッシュの理由は、ユーザーがメイン アクティビティにあるときのユーザーの null 値です。多くのユーザーが推奨するように、メイン アクティビティをメイン ラウチャーとして作成し、ユーザーがそこからログインしているかどうかを確認します。しかし、何もうまくいきませんでした。
ログイン アクティビティとメイン アクティビティのコード全体を含めました。「driverId」をプリファレンスに保存したいのですが、アプリが再起動されるたびに、メイン アクティビティがプリファレンスから「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));
};
}
}
}
したがって、ユーザーが正常にログインすると、「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; }
}
}