第一行代码Andorid——登录记住密码

android 专栏收录该内容
7 篇文章 0 订阅

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">使用广播实现强制下线功能,使用SharedPreferences记住用户名密码</span>

BaseActivity.java

public class BaseActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityCollector.addActivity(this);
    }


    @Override
    protected void onStop() {
        super.onStop();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }
}

LoginActivity.java

public class LoginActivity extends BaseActivity {

    private EditText etPhone;
    private EditText etPassword;
    private Button btnLogin;
    private CheckBox cbRememberPassword;

    private SharedPreferences sp;
    private SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        etPhone = (EditText) findViewById(R.id.account);
        etPassword = (EditText) findViewById(R.id.password);
        btnLogin = (Button) findViewById(R.id.login);
        cbRememberPassword = (CheckBox) findViewById(R.id.remember_pass);
        sp = PreferenceManager.getDefaultSharedPreferences(this);

        boolean isRemember = sp.getBoolean("remember_password", false);
        if(isRemember) {
            //将记住的电话号码和密码设置到文本框中
            etPhone.setText(sp.getString("phone", ""));
            etPassword.setText(sp.getString("password", ""));
            cbRememberPassword.setChecked(true);
        }

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = etPhone.getText().toString();
                String password = etPassword.getText().toString();
                //校验用户名和密码
                if(phone.equals("jxd") && password.equals("12345")) {
                    editor = sp.edit();
                    if(cbRememberPassword.isChecked()) {
                        editor.putBoolean("remember_password", true);
                        editor.putString("phone", phone);
                        editor.putString("password", password);
                    } else {
                        editor.clear();
                    }
                    editor.commit();
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(LoginActivity.this, "电话号或密码错误", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private Button btnForceOff;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnForceOff = (Button) findViewById(R.id.btn_forceOff);
        btnForceOff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.baodage.mylogin.FORCE_OFFLINE");
                sendBroadcast(intent);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

自定义强制下线的广播接收器

public class ForceOfflineReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, Intent intent) {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
        dialogBuilder.setTitle("警告");
        dialogBuilder.setMessage("强制退出,请重新登录");
        dialogBuilder.setCancelable(false);
        dialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //销毁所有活动
                ActivityCollector.finishAll();
                Intent intent = new Intent(context, LoginActivity.class);
                //在广播中启动activity,加上此标志
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
        });
        AlertDialog dialog = dialogBuilder.create();
        //设置对话框类型为TYPE_SYSTEM_DIALOG,不然无法再广播接收器中弹出
        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        dialog.show();
    }
}

用到的工具类ActivityCollector.java

public class ActivityCollector {

    private static List<Activity> activities = new ArrayList<Activity>();

    public static void addActivity(Activity activity) {
        activities.add(activity);
    }

    public static void removeActivity(Activity activity) {
        activities.remove(activity);
    }

    public static void finishAll() {
        for (Activity activity : activities) {
            if(!activity.isFinishing()) {
                activity.finish();
            }
        }
    }
}

相应的布局文件

activity_login.xml

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:stretchColumns="1" >

    <TableRow>
        <TextView
            android:layout_height="wrap_content"
            android:text="手机号" />

        <EditText
            android:id="@+id/account"
            android:layout_height="wrap_content"
            android:hint="输入手机号" />
    </TableRow>

    <TableRow>
        <TextView
            android:layout_height="wrap_content"
            android:text="手机号" />

        <EditText
            android:id="@+id/password"
            android:layout_height="wrap_content"
            android:inputType="textPassword" />
    </TableRow>

    <TableRow>
        <CheckBox
            android:id="@+id/remember_pass"
            android:layout_height="wrap_content" />

        <TextView
            android:layout_height="wrap_content"
            android:text="记住密码" />
    </TableRow>

    <TableRow>
        <Button
            android:id="@+id/login"
            android:layout_height="wrap_content"
            android:layout_span="2"
            android:text="登录" />
    </TableRow>

</TableLayout>

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<Button
    android:id="@+id/btn_forceOff"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="发送强制下线广播" />

</RelativeLayout>

配置文件AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.baodage.mylogin"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".LoginActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity">
        </activity>
        <receiver android:name=".ForceOfflineReceiver">
            <intent-filter>
                <action android:name="com.baodage.mylogin.FORCE_OFFLINE"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>




  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 扫一扫,分享海报

参与评论 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值