首先呢,看到这么长的标题,是不是感觉这些功能有点难以实现呢,哈哈,其实并没有想象中的那么复杂,下面就跟着笔者来一起学习一下这些功能是怎么实现的吧!
1.建立一个所有活动的父类,继承自AppcompatAvtivity类,用来实现全局广播,与强制下线功能相关联:
package com.example.pc_ly.dl;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
/**
* Created by pc_ly on 2018/10/29.
*/
public class BaseActivity extends AppCompatActivity {//所有活动继承的一个类,用来实现全局广播,
Intent aa=getIntent();
private Focreof receiver;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityCollector.addAvtivity(this);
}
protected void onResume(){
super.onResume();
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction("com.example.office");
receiver=new Focreof();
registerReceiver(receiver,intentFilter);
}
protected void onPause(){
super.onPause();
if(receiver!=null){
unregisterReceiver(receiver);
receiver=null;
}
}
protected void onDestroy(){
super.onDestroy();
ActivityCollector.removeActivity(this);}
class Focreof extends BroadcastReceiver{//当广播成功响应时,弹出一个对话框,显示一些信息,并且之后会回到登录的界面
public void onReceive(final Context context, final Intent intent){
;
AlertDialog.Builder builder=new AlertDialog.Builder(context);
builder.setTitle("警告");
builder.setMessage("Dear:"+intent.getStringExtra("t")+"! You are forced to be offline. Please try to login again.");
builder.setPositiveButton("OK",new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int which){
ActivityCollector.finishAll();
Intent intent=new Intent(context,MainActivity.class);
context.startActivity(intent);
}
});
builder.show();
}
}
}
2.建立一个管理所有活动的类:
package com.example.pc_ly.dl;
import android.app.Activity;
import java.util.ArrayList;
import java.util.List;
/**
* Created by pc_ly on 2018/10/29.
*/
public class ActivityCollector {//管理所有活动
public static List activities=new ArrayList<>();
public static void addAvtivity(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();
}
}
activities.clear();
}
}
3.建立一个初始化数据库的类,并创建对应的表
package com.example.pc_ly.dl;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import java.sql.SQLClientInfoException;
/**
* Created by pc_ly on 2018/11/20.
*/
public class DateBaseHelper extends SQLiteOpenHelper {
public static final String CREATE_BOOK="create table userData ("
+ "id text, "
+"password text)";//创建表的语句
private Context mContext;
public DateBaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,int version){//初始化一个数据库
super(context,name,factory,version);
mContext=context;
}
public void onCreate(SQLiteDatabase db){
db.execSQL(CREATE_BOOK);//执行创建表的语句
Toast.makeText(mContext,"Create succeed",Toast.LENGTH_SHORT).show();
}
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
}
}
4.先将登录的界面通过代码写出来,这个比较简单,我就直接上代码了
效果大致是这个样子:
其中的记住密码的复选框是有checkbox定义的,然后下拉箭头是一张图片,大家可以去网上下载,然后利用Drawableright属性把它添加到账号框里面去,然后这个界面就做好啦。
5.这一步呢就是将登录界面要实现的功能的代码写出来,代码如下:
package com.example.pc_ly.dl;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ListPopupWindow;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends BaseActivity{
private SharedPreferences pref;//利用sharePREfreences来保存数据
private SharedPreferences.Editor editor;//用来保存密码的
private DateBaseHelper dphelp;
private ListPopupWindow listPopupWindow;
private EditText accountEdit;
private EditText passwordEdit;
private Button login;
private Button zhuce;
private CheckBox rember;
private String list[];
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dphelp=new DateBaseHelper(this,"Userss.db",null,1);//数据库的初始化
rember=(CheckBox)findViewById(R.id.rember_1) ;//这个是复选框,用来选择是否选中密码的
login=(Button)findViewById(R.id.button_1);
zhuce=(Button)findViewById(R.id.zhuce_);//初始化
//list.add("li");
listPopupWindow=new ListPopupWindow(MainActivity.this);
accountEdit=(EditText)findViewById(R.id.account) ;
passwordEdit=(EditText)findViewById(R.id.password) ;
pref=PreferenceManager.getDefaultSharedPreferences(this);
Boolean isrember=pref.getBoolean("rember_pass",false);//初始设置记住密码为false
DateBaseHelper database=new DateBaseHelper(this,"Userss.db",null,1);
if(isrember){
int username=perf.getInt("username",0)-1;
String id=pref.getString("account"+username,"");
String pass=pref.getString("password"+username,"");
accountEdit.setText(id);
passwordEdit.setText(pass);//把保存的账号和密码读取出来
rember.setChecked(true);
}
zhuce.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {//点击注册跳到注册的页面
Intent intent=new Intent(MainActivity.this,Zhuche.class);
startActivity(intent);
}
});
login.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
accountEdit=(EditText)findViewById(R.id.account);//与相应的文本框对应起来
passwordEdit=(EditText)findViewById(R.id.password);
String userName=accountEdit.getText().toString();//获取文本框的数据
String passWord=passwordEdit.getText().toString();
if (login(userName,passWord)) {
Toast.makeText(MainActivity.this, "登陆成功,欢迎来到新的世界", Toast.LENGTH_SHORT).show();//成功了弹出登陆成功
editor=pref.edit();
if(rember.isChecked()){//复选框是否被选中
int username=pref.getInt("username",0);
editor.putBoolean("rember_pass",true);//把记住密码设置为true
editor.putString("account"+username,userName);
editor.putString("password"+username,passWord);//把密码和账号分别保存到account和password里面
editor.putInt("username",username+1);
}
else{
editor.clear();//清空editor保存的东西
}
editor.apply();//启用editoy
String data=userName;
Intent intent=new Intent(MainActivity.this,denglv.class);
intent.putExtra("ex",data);//把当前登陆成功的账号的数据传递给下一个活动,用来显示是谁登陆成功了
startActivity(intent);
}
else {
Toast.makeText(MainActivity.this, "登陆失败", Toast.LENGTH_SHORT).show();//失败,弹出登陆失败
}
}});
accountEdit.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {//设置监听事件
final int DRAWABLE_LEFT = 0;
final int DRAWABLE_TOP = 1;
final int DRAWABLE_RIGHT = 2;
final int DRAWABLE_BOTTOM = 3;
if (event.getAction() == MotionEvent.ACTION_UP) {
if (event.getX() >= (accountEdit.getWidth() - accountEdit
.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
//当点击了箭头位置的时候回调用下面的函数,显示出下拉框
accountEdit.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.jiantou), null);
showListPopulWindow();
return true;
}
}
return false;
}
});
}
public void showListPopulWindow(){//用来显示下拉框
final String acc[]=new String[pref.getInt("username",0)];//定义一个账号数组,长度为选择记住密码的登录成功的账号个数
final String pas[]=new String[pref.getInt("username",0)];//定义一个密码数组,长度为选择记住密码的登录成功的账号个数
for(int a=0;a(this,
android.R.layout.simple_list_item_1, acc));//把账号的数据显示到下拉列表里面去
listPopupWindow.setAnchorView(accountEdit);
listPopupWindow.setModal(true);
listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {//设置项点击监听
@Override
public void onItemClick(AdapterView adapterView, View view, int i, long l) {
accountEdit.setText(acc[i]);//当选中下拉框的某一个选项的时候,把选择的选项内容展示在EditText上
passwordEdit.setText(pas[i]);//将选中的账号的密码显示出来,显示在面板上,
listPopupWindow.dismiss();//如果已经选择了,隐藏起来
}
});
listPopupWindow.show();
}
public boolean login(String username,String password) {//验证此账号密码是否正确
SQLiteDatabase db = dphelp.getWritableDatabase();
String sql = "select * from userData where id=? and password=?";//将登录时填的账号和密码在数据库里面进行查询,如果存在该数据,则返回true,否则返回false
Cursor cursor = db.rawQuery(sql, new String[] {username, password});
if (cursor.moveToFirst()) {
cursor.close();
return true;
}
return false;
}
}
上面的注释比较详细,就不一一介绍啦
6.将注册的界面通过代码写出来:
7.将注册界面要实现的功能通过代码写出来:
package com.example.pc_ly.dl;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Zhuche extends BaseActivity {
private DateBaseHelper dphelper;
private EditText a,b;
private Button an1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zhuche);
dphelper=new DateBaseHelper(this,"Userss.db",null,1);
an1=(Button)findViewById(R.id.button_111);
an1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//dphelper.getWritableDatabase();
a=(EditText)findViewById(R.id.account111);
b=(EditText)findViewById(R.id.password111) ;
String newname =a.getText().toString();
String password=b.getText().toString();
Log.d("Zhuche","sss");
if (CheckIsDataAlreadyInDBorNot(newname)) {
Toast.makeText(Zhuche.this,"该用户名已被注册,注册失败",Toast.LENGTH_SHORT).show();
}
else {
if (register(newname, password)) {
Toast.makeText(Zhuche.this, "恭喜您 注册成功,即将返回登录界面", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(Zhuche.this,MainActivity.class);
startActivity(intent);
}}
}
});
}
//向数据库插入数据
public boolean register(String username,String password){
SQLiteDatabase db= dphelper.getWritableDatabase();
/*String sql = "insert into userData(name,password) value(?,?)";
Object obj[]={username,password};
db.execSQL(sql,obj);*/
ContentValues values=new ContentValues();
values.put("id",username);
values.put("password",password);
db.insert("userData",null,values);
db.close();
//db.execSQL("insert into userData (name,password) values (?,?)",new String[]{username,password});
return true;
}
//检验用户名是否已存在
public boolean CheckIsDataAlreadyInDBorNot(String value){
SQLiteDatabase db=dphelper.getWritableDatabase();
String Query = "Select * from userData where id =?";
Cursor cursor = db.rawQuery(Query,new String[] { value });
if (cursor.getCount()>0){
cursor.close();
return true;
}
cursor.close();
return false;
}
}
8.登录成功之后,会跳到一个新的界面,界面的布局代码如下:
9.当点击按钮之后,会实现强制下线的功能,代码如下:
package com.example.pc_ly.dl;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class denglv extends BaseActivity{
private DateBaseHelper hp;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent=getIntent();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_denglv);
Button force=(Button)findViewById(R.id.button_2);
textView=(TextView)findViewById(R.id.text_1) ;
textView.setText("Hi,"+intent.getStringExtra("ex"));//显示你的名字出来
force.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent aa=getIntent();
String data=aa.getStringExtra("ex");
Intent intent=new Intent("com.example.office");
intent.putExtra("t",data);
sendBroadcast(intent);//点击按钮会强制退出,并利用intent传递数据
}
});
}
}
然后代码差不多就是这个样子啦,最后再贴几张效果图:
有啥疑问的欢迎留言哦
其他博客的链接:
Github个人网站 知乎 简书
欢迎各位访问哦,这次就到这里啦!