2012-10-09 160 views
0

我正在開發需要用戶登錄的android應用程序。此應用程序依賴於Web服務器來驗證用戶的詳細信息,以便用戶可以登錄。我的問題從這裏開始,登錄用戶沒有問題,但是當用戶按回家鍵並返回到應用程序時,顯示登錄屏幕這是非常糟糕的。登錄時保存用戶憑證

我聽說過SharedPrefrences,但我不知道如何使用此保存用戶詳細信息,以便用戶可以直接移動到主要活動。

我已將我的源代碼包含在這裏。如果有人熟悉SharedPrefrences可以幫助我解決這個問題。我的鱈魚例子會有幫助。

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")] 
    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)); 
      }; 
     } 
    } 
} 

回答

0

不確定monodroid,但通常在您的應用程序中,所有需要授權的活動必須從一個活動中進行分類,該活動檢查onResume用戶是否有有效會話(您可以在登錄後存儲有關成功登錄或會話ID的標誌,例如在你的Application類或任何適當的單身人士)。然後

  • 如果檢查失敗 - 回報用戶登錄屏幕
  • 如果全成 - 什麼都不做,只是讓他們的活動,他希望

爲了避免活動棧(問題按home鍵返回到什麼登錄屏幕)並從中刪除LoginActivity在清單或相關屬性中使用android:noHistory="true"通過意圖

2
public void savePrefrences(String key, String value) 
    { 
     SharedPreferences prefs = context.getSharedPreferences(context.getApplicationContext().getPackageName(), 0); 
     prefs.edit().putString(key, value).commit(); 
    } 

public String getPrefrences(String key) 
    { 
     SharedPreferences prefs = context.getSharedPreferences(context.getApplicationContext().getPackageName(), 0); 
     return prefs.getString(key, ""); 
    } 

這樣即使你閉上你的信息將可在該應用的任何然後重新打開。

上的登錄屏幕 - 當用戶執行一次成功登錄調用savePrefrences("hasLoggenInPref", "true"); 現在,每當用戶重新進入登陸界面 - 撥打getPrefrences("hasLoggenInPref"),檢查其equals"true",如果是的話,跳轉到你的主屏幕,如果沒有,顯示登錄屏幕。

您應該從啓動畫面或其他東西調用getPrefrences函數,如果返回true,則打開您的應用程序,如果沒有,則打開登錄屏幕。

當用戶註銷時只需調用savePrefrences("hasLoggenInPref", "false");

希望這有助於。

+0

可以請您指教我如何在上下文中將此實現到我的應用程序。這真的會幫助我。 –

+0

編輯我的答案。 – Givi