0

我有将被定向到登录活动的启动活动,如果登录为真,那么用户将直接回到主页,但是当用户按下主页时,应用程序将自动关闭。但问题是当用户打开应用程序时,他们必须再次登录,即使他们之前没有注销。那么如何将水溅到家庭活动中呢?我已阅读,要处理它,我必须使用 sharedpreferences 所以我必须使用它,但我不知道如何使用它自动处理登录。这是我的垃圾:

public class SplashEpolicy extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    //hide title bar
    BasicDisplaySettings.toggleTaskBar(SplashEpolicy.this, false);
    //show status bar
    BasicDisplaySettings.toggleStatusBar(SplashEpolicy.this, true);

    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash_epolicy);

    Thread timer = new Thread() {
        public void run() {
            try {
                //this is configuration for how long the splash will be shown.
                //
                int time = Integer.parseInt(getResources().getString(R.string.splashTransTime));
                sleep(time);
            } catch (InterruptedException e) {
                // TODO: handle exception
                e.printStackTrace();
            } finally {
                //line below is for direct new activity that will be run after 
                //current activity finished.
                Intent intent = new Intent(SplashEpolicy.this,EpolicyMainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);      
                finish();
            }
        }
    };
    timer.start();      
}

这是我包含共享首选项的登录活动:

                String KEY = jo.getString("key");
                SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
                SharedPreferences.Editor editor = settings.edit();
                editor.putString("etUser", strUser);
                editor.putString("key",KEY);
                editor.commit();
                System.out.println(KEY+""+"key"+""+"etUser");

                Dialog.dismiss();
                Intent i = new Intent(LoginActivity.this,EpolicyMainTab.class);
                startActivity(i);

        }
        }catch (JSONException e) {
            e.printStackTrace();
        }

所以这是我的家(EpolicyListPolisActivity):

    public class EpolicyListPolis extends ListActivity {
    static String PEMEGANG="PEMEGANG";
    static String POLIS="POLIS";
    static String STATUS="STATUS";
    static String TERTANGGUNG="TERTANGGUNG";
    String KEY, strUser;
    List NasabahList= new ArrayList();
    private ProgressDialog Dialog;
    private String strStoragePath = "",
            strNameFileDiv = "";
    ImageView LogoutButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle(R.string.Nomor_Polis);


        setContentView(R.layout.epolicy_list_polis);
        SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
        strUser= settings.getString("etUser", null);
        KEY = settings.getString("key", null);
        LogoutButton=(ImageView)findViewById(R.id.LogoutButton);

        new NasabahAsyncTask().execute();

        LogoutButton.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                dialogSignOut();
            }
        });
            }
public class NasabahAsyncTask extends AsyncTask<Void, Void, String>{
    String url = ("http://www.example.com?i="+strUser+"&k="+KEY);
    public NasabahAsyncTask() {
        this.url=url;
        // TODO Auto-generated constructor stub
    }

    protected void onPreExecute() {
        super.onPreExecute();   
        Dialog = ProgressDialog.show(EpolicyListPolis.this, "", "Melakukan Pengambilan Data");
    }

@Override
protected String doInBackground(Void... params) {
    String result="";
    try {
        result=Connection.get(url);
    }catch (Exception e){
        result=" ";
        Log.d("test viewer",e.getMessage());
    }
    return result;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    fetchResponse(result.replace("\n", "").trim());

    ListAdapter adapter = new SimpleAdapter(
            EpolicyListPolis.this, NasabahList, R.layout.epolicy_polis_listitem,
            new String[] {POLIS, PEMEGANG, TERTANGGUNG, STATUS}, new int [] {R.id.polis, R.id.pemegang, R.id.tertanggung, R.id.status});

        setListAdapter(adapter);
    Dialog.dismiss();
    ListView lv = getListView();

    lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            String POLIS = ((TextView)view.findViewById(R.id.polis)).getText().toString();

            SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString("POLIS", POLIS);
            editor.commit();
            }
}

private void fetchResponse(String result) {
    // TODO Auto-generated method stub
    if (!result.equals("")) {
        try {
            JSONArray jsonArray = new JSONArray(result);
            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject jsonObject = jsonArray.getJSONObject(i);
                HashMap<String, String> map = new HashMap<String, String>();
                if (jsonObject.has("PEMEGANG")) 
                    map.put("PEMEGANG", jsonObject.get("PEMEGANG").toString());
                if (jsonObject.has("POLIS")) 
                    map.put("POLIS", jsonObject.get("POLIS").toString());
                if (jsonObject.has("STATUS")) 
                    map.put("STATUS", jsonObject.get("STATUS").toString());
                if (jsonObject.has("TERTANGGUNG")) 
                    map.put("TERTANGGUNG", jsonObject.get("TERTANGGUNG").toString());
                NasabahList.add(map);
                System.out.println("json oke");
}
        }catch (JSONException e) {

            e.printStackTrace();
        }

        }
    }
@Override
public void onBackPressed() {
    dialogExit();
}
public void dialogExit()
{
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("do you want to exit?")
           .setCancelable(false)
           .setPositiveButton("Ya", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   Intent itSplashEnd = new Intent(EpolicyListPolis.this, SplashEnd.class);
                   //setIntent.addCategory(Intent.CATEGORY_HOME);
                   itSplashEnd.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
                   itSplashEnd.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                   startActivity(itSplashEnd);
                   finish();
                   System.exit(0);
               }
           })
           .setNegativeButton("no", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });
    AlertDialog alert = builder.create();
    alert.show();
}

public void dialogSignOut()
{
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Sign out?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
               // what will i do here?

                   Intent itSignOut = new Intent(EpolicyListPolis.this, EpolicyMainActivity.class);
                   itSignOut.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                   startActivity(itSignOut);
                   finish();
               }
           })
           .setNegativeButton("no", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });
    AlertDialog alert = builder.create();
    alert.show();
}

    }

那么如何在不使用共享首选项再次登录活动的情况下自动登录到主页?以及如何在每次用户退出时清除保存在 sharedpreferences 中的数据?

4

5 回答 5

2

我不知道 Gokul Nath 的回答有什么问题,但让我们再试一次。您可以通过简单的 if 来检查用户是否已经登录。首先你加载你的用户数据(假设用户名和密码):

SharedPreferences prefs = this.getSharedPreferences("com.project.myProject", Context.MODE_PRIVATE);
String savedUser = "com.project.myProject.savedUser";
String user = prefs.getString(savedUser, "none"); // return "none" if user is not logged in
String savedPass = "com.project.myProject.savedPass";
String pass = prefs.getString(savedPass, "none");

if (user.equalsIgnoreCase("none") || pass.equalsIgnoreCase("none")) {
    // Show a log in dialog and/or other stuff to let user log in
} else {
    // Launch your main interface
}

如果您是第一次或注销后启动应用程序,这将有效。在注销时,您可以像这样清除所有 SharedPreferences(注意:清除或重置 SharedPreferences 对我来说是一样的):

YourActivity.this.getSharedPreferences("com.project.myProject", Context.MODE_PRIVATE).edit().clear().commit();

通过这样做,如果用户再次启动您的应用程序,他将不得不再次登录。

我在您的代码中看到的另一件事是:

Intent intent = new Intent(SplashEpolicy.this,EpolicyMainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);      
finish();

我猜你 addFlags 是有意的,因为当你按下后退按钮时,你的应用程序会返回 SplashEpolicy。如果我是对的,您可以在您的代码中做得更好,方法是在您的清单中添加这一行“android:noHistory="true""(如果我错了,请跳过这部分答案):

<activity
    android:name="com.project.myProject.SplashEpolicy"
    android:label="@string/app_name"
    android:noHistory="true" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

有了这个,您的飞溅活动将不会留下历史痕迹。它不会保留在任务的活动堆栈中,因此用户将无法返回到它(cit. Android Dev 站点)。

于 2013-06-13T09:29:50.003 回答
2

自动登录:

检查登录详细信息是否保存在SharedPreferences. 如果找到,您可以检索该值并自动登录。

SharedPreferences prefs = this.getSharedPreferences("YOUR_PREF_NAME", Context.MODE_PRIVATE);

String loginID = prefs.getString("LOGIN_ID", "");
String loginPWD = prefs.getString("LOGIN_PWD", "");

if (loginID.length()>0 && loginPWD.length()>0) {
     //YOUR LOGIN CODE
} else {
     //SHOW PROMPT FOR LOGIN DETAILS
}

要在退出时清除数据,您可以在退出命令中使用以下代码:

SharedPreferences prefs = this.getSharedPreferences("YOUR_PREF_NAME", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString("LOGIN_ID", "");     //RESET TO DEFAULT VALUE
editor.putString("LOGIN_PWD", "");     //RESET TO DEFAULT VALUE
editor.commit();
于 2013-06-13T08:26:18.147 回答
0

您可以使用布尔值来跟踪登录状态,也就是说,如果已登录,则为 true,否则为 false。您可以在初始屏幕上检查此布尔变量的值,以便打开登录对话框,以防万一它为假。这是存储上述布尔值的简单方法:

SharedPreferences sharedPrefs = getSharedPreferences("youPrefsFile", 0);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putBoolean("isLoggedIn", true);
editor.commit();

还有一个简单的方法来获得它的价值:

SharedPreferences settings = getSharedPreferences("youPrefsFile",0);
boolean isLoggedin = settings.getBoolean("isLoggedIn", false);

希望能帮助到你。

于 2013-06-13T08:30:23.200 回答
0

您可以通过使用共享首选项来做到这一点。使用一个布尔标志作为

        boolean signedflag=false;

将此标志存储在共享首选项中。

如果'signedflag = false'在登录时检查此标志,则仅将'登录详细信息(登录名和密码)'存储到共享首选项,否则使用现有值。

当您注销时,清除所有共享首选项变量并再次设置signedflag=false。

于 2013-06-13T08:32:44.260 回答
0

成功登录后将loggedInUser保存在共享首选项中,例如:

SharedPreferences sharedPrefs = getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putBoolean("isLoggedIn", true);
editor.commit();

并且检查是这样登录的:

SharedPreferences prefs = this.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
boolean isLoggedIn = prefs.getString(isLoggedIn, false); // return "false" if user is not logged in

if (!isLoggedIn) {
    // Show a log in dialog and/or other stuff to let user log in
} else {
    // Launch your main interface
}
于 2020-10-12T04:45:27.900 回答