博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
整合大量開源庫溫習基礎項目(一)
阅读量:6814 次
发布时间:2019-06-26

本文共 15752 字,大约阅读时间需要 52 分钟。

轉載請注明出處:

有一段時間沒好好寫文章了,然後就把之前的那個滑動解鎖的內容又繼續升級了下,準備在這之後做進一步的衍生,上次的例子

這一次例子的效果

这里写图片描述

項目結構:

这里写图片描述

完成如下功能-進入APP-對網絡,用戶狀態的判斷-跳轉至登錄/註冊的介面-登錄狀態的判斷(註冊部分邏輯未寫,按照實際需求做吧)

為什麼要這麼做?

1.沒事幹的時候找點事情做做,溫習一下技能
2.在實操的過程中對自己的實現方式做改進(主要是設計和實現的思路,優化什麼的之後再做吧)

廢話不多直接上代碼(適配做的是谷歌兒子7的,如果正常手機看不習慣的話,請見諒)

基類 BaseActivity

public abstract class BaseActivity extends Activity {
protected static final String TAG = BaseActivity.class.getName() + ".TAG"; Intent network; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayout()); findById(); setListener(); logic(); //监听网络 if (network == null) { network = new Intent(BaseActivity.this, NetworkStateService.class); } startService(network); } //FindById protected abstract void findById(); //setListener protected abstract void setListener(); //Logic protected abstract void logic(); protected abstract int getLayout(); //判断是否有网络 protected boolean isNetworkConnected(Context context) { if (context != null) { ConnectivityManager mConnectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); if (mNetworkInfo != null) { return mNetworkInfo.isAvailable(); } } return false; } //判断WIFI public boolean isWifiConnected(Context context) { if (context != null) { ConnectivityManager mConnectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWiFiNetworkInfo = mConnectivityManager .getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (mWiFiNetworkInfo != null) { return mWiFiNetworkInfo.isAvailable(); } } return false; } //关闭网络判断 protected void stopNetworkService() { if (network != null) { stopService(network); } } protected void ShowToast(Context context,String str){ Toast.makeText(context,str,Toast.LENGTH_SHORT).show(); } @Override protected void onDestroy() { super.onDestroy(); LogUtils.d("---->BaseActivity onDestroy stopNetworkService"); stopNetworkService(); }}

這樣的一個類,在我之前的項目中有出現類似的,主要是方便開發

整個程序的主介面 Main

public class Main extends BaseActivity {
final static String TAG = Main.class.getName() + ".TAG"; private final static boolean DEBUG = true; private ImageView imageView; private YoYo.YoYoString rope; //計時器 private int recLen = 5; Timer timer = new Timer(); TimerTask task = new TimerTask() { public void run() { recLen--; //修改界面的相关设置只能在UI线程中执行 runOnUiThread(new Runnable() { public void run() { if (recLen < 3) { timer.cancel(); goToNext(); } } }); } }; @Override protected void findById() { imageView = (ImageView) findViewById(R.id.imageView); } @Override protected void setListener() { } @Override protected void logic() { //漸漸放大 rope = YoYo.with(Techniques.ZoomInUp).duration(1800).playOn(imageView); timer.schedule(task, 1000, 1000); } @Override protected int getLayout() { return R.layout.main; } @Override protected void onDestroy() { super.onDestroy(); LogUtils.d("---->Main onDestroy stopNetworkService"); stopNetworkService(); } private void goToNext() { if (isNetworkConnected(Main.this)) { SharedPreferences sharedPreferences = getSharedPreferences("userinfo", Activity.MODE_PRIVATE); String name=sharedPreferences.getString("username", ""); Intent a; if(name.equals(null) || name.length() <= 0){ a = new Intent(Main.this, RegisterActivity.class); }else{ a = new Intent(Main.this, LoginActivity.class); } startActivity(a); overridePendingTransition(R.anim.scale_in, R.anim.alpha_out); } else { Intent intent = null; // 先判断当前系统版本 if (android.os.Build.VERSION.SDK_INT > 10) { // 3.0以上 intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS); } else { intent = new Intent(); intent.setClassName("com.android.settings", "com.android.settings.WirelessSettings"); } startActivity(intent); } }}

登錄

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
final static String TAG = LoginActivity.class.getName() + ".TAG"; private long exitTime = 0; private IconEditText users, password; private Button login; private TextView go_to_register; private String User, Password; private YoYo.YoYoString rope; SharedPreferences sharedPreferences; SharedPreferences.Editor localEditor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LogUtils.d("--->" + TAG + " onCreate"); setContentView(R.layout.activity_login); sharedPreferences = getSharedPreferences("userinfo", Activity.MODE_PRIVATE); localEditor = sharedPreferences.edit(); users = (IconEditText) findViewById(R.id.user); password = (IconEditText) findViewById(R.id.password); go_to_register = (TextView) findViewById(R.id.go_to_reg); login = (Button) findViewById(R.id.login); login.setOnClickListener(this); go_to_register.setOnClickListener(this); } @Override protected void onResume() { super.onResume(); } @Override public void onClick(View v) { int flag = v.getId(); switch (flag) { case R.id.login: logic(); break; case R.id.go_to_reg: localEditor.clear().commit(); PageSwitch.goToRegisterActivity(LoginActivity.this); break; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { if ((System.currentTimeMillis() - exitTime) > 2000) { Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show(); exitTime = System.currentTimeMillis(); } else { //返回桌面 Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 注意本行的FLAG设置 startActivity(intent); } return true; } return super.onKeyDown(keyCode, event); } private void logic() { User = users.getEditText().getText().toString(); Password = password.getEditText().getText().toString(); if (!User.equals(sharedPreferences.getString("username", "")) || !Password.equals(sharedPreferences.getString("password", ""))) { makeAnim(users, password); } else { Toast.makeText(LoginActivity.this, "Login Success", Toast.LENGTH_SHORT).show(); } } private void makeAnim(View view1, View view2) { Techniques technique = (Techniques) users.getTag(); rope = YoYo.with(technique.Shake) .duration(1200) .interpolate(new AccelerateDecelerateInterpolator()) .withListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { } @Override public void onAnimationCancel(Animator animation) { Toast.makeText(LoginActivity.this, "canceled", Toast.LENGTH_SHORT).show(); } @Override public void onAnimationRepeat(Animator animation) { } }) .playOn(view1); rope = YoYo.with(technique.Shake) .duration(1200).playOn(view2); } //重寫finish實現動畫效果 @Override public void finish() { super.finish(); overridePendingTransition(R.anim.scale_in, R.anim.alpha_out); } @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); } @Override protected void onDestroy() { super.onDestroy(); }}

這邊的.interpolate(new AccelerateDecelerateInterpolator()) .withListener(new Animator.AnimatorListener()可以不調用,看你具體業務需求了

註冊

public class RegisterActivity extends BaseActivity implements View.OnClickListener {
final static String TAG = RegisterActivity.class.getName() + ".TAG"; private long exitTime = 0; private int recLen = 61; private boolean isTiming = false; private IconEditText password, user, phone, message; private Button registerButton, send_msg; private TextView go_to_login; Timer timer = new Timer(); TimerTask task = new TimerTask() { public void run() { recLen--; //修改界面的相关设置只能在UI线程中执行 runOnUiThread(new Runnable() { public void run() { if (recLen >= 0) { mHandler.sendEmptyMessage(recLen); } else { timer.cancel(); recLen = 61; } } }); } }; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); int reclenInt = msg.what; if (reclenInt > 0) { send_msg.setClickable(false); send_msg.setText(reclenInt + "秒"); } else { send_msg.setClickable(true); send_msg.setText(getResources().getString(R.string.send_Msg)); } } }; @Override protected void findById() { password = (IconEditText) findViewById(R.id.password); user = (IconEditText) findViewById(R.id.user); phone = (IconEditText) findViewById(R.id.phone); message = (IconEditText) findViewById(R.id.message); registerButton = (Button) findViewById(R.id.registerbutton); send_msg = (Button) findViewById(R.id.send_msg); go_to_login = (TextView) findViewById(R.id.go_to_login); } @Override protected void setListener() { registerButton.setOnClickListener(this); send_msg.setOnClickListener(this); go_to_login.setOnClickListener(this); } @Override protected void logic() { } @Override protected int getLayout() { return R.layout.activity_register; } @Override public void onClick(View v) { int flag = v.getId(); switch (flag) { case R.id.registerbutton: if (LoginLogic()) { //異步操作 ShowToast(RegisterActivity.this,"Reguster Success"); } break; case R.id.send_msg: if (isTiming == false) { sendMsg(); } break; case R.id.go_to_login: PageSwitch.goToLoginActivity(RegisterActivity.this); break; } } @Override protected void onResume() { super.onResume(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { if ((System.currentTimeMillis() - exitTime) > 2000) { Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show(); exitTime = System.currentTimeMillis(); } else { //返回桌面 Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 注意本行的FLAG设置 startActivity(intent); } return true; } return super.onKeyDown(keyCode, event); } @Override protected void onDestroy() { super.onDestroy(); LogUtils.d("---->RegisterActivity onDestroy stopNetworkService"); stopNetworkService(); } //重寫finish實現動畫效果 @Override public void finish() { super.finish(); overridePendingTransition(R.anim.scale_in, R.anim.alpha_out); } //發短信,模擬的 你懂的 private void sendMsg() { timer.schedule(task, 1000, 1000); } //註冊業務邏輯 private boolean LoginLogic() { //申明一個集合來處理一系列判斷,一個個寫 太麻煩了。。感覺還有更簡便的。有空想想 Hashtable
hashMap = new Hashtable(); hashMap.put("message", message.getText().toString()); hashMap.put("phone", phone.getText().toString()); hashMap.put("password", password.getText().toString()); hashMap.put("username", user.getText().toString()); //遍曆Map也會有性能問題,但是這也就 4個字符串,又不多,就隨便了 // 在tools的PhoneUtils類裏 有一些符合操作的工具類,可以使用 Iterator iterator = hashMap.entrySet().iterator(); SharedPreferences sharedPreferences=getSharedPreferences("userinfo", Activity.MODE_PRIVATE); SharedPreferences.Editor localEditor = sharedPreferences.edit(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); String key = (String) entry.getKey(); String val = (String) entry.getValue(); LogUtils.d("--->RegisterActivity LoginLogic()" + "key :" + key + " val " + val); if (val.equals(null) || val.length() <= 0) { ShowToast(RegisterActivity.this, key + " No fill"); localEditor.clear().commit(); return false; }else{ localEditor.putString(key,val); localEditor.commit(); } } return true; }}

這邊用SharedPreferences 作為本地化的一些操作(因為會加一個記住密碼這樣的東西,數據庫啊SD卡都行,看你喜歡了 SP方便點。 但是記得加密啊!!)

頁面跳轉類(現有的代碼裏也有一Intent方可以加到裏面來,之後再做優化吧)

public class PageSwitch {    public static void goToLoginActivity(Activity activity) {        Intent intent=new Intent(activity,LoginActivity.class);        activity.startActivity(intent);    }    public static void goToRegisterActivity(Activity activity) {        Intent intent=new Intent(activity,RegisterActivity.class);        activity.startActivity(intent);    }}

註冊的XML

登錄的XML

還有一些工具類和自定義控件就在源碼中看吧,源碼地址:記得點暫哦!!!

有什麼希望我加的也可以留言,需求方面 沒有什麼很大的頭緒,不知道要做什麼。

你可能感兴趣的文章
SQL物化视图 自动更新 定时刷新
查看>>
express框架应用接入阿里云函数计算
查看>>
几行代码实现ofo首页小黄人眼睛加速感应转动
查看>>
317TABLE ACCESS BY INDEX ROWID BATCHED3
查看>>
MapReduce Shuffle原理 与 Spark Shuffle原理
查看>>
题解 P3386 【【模板】二分图匹配】
查看>>
李彦宏:人工智能的互联网时代已经到来
查看>>
游标概念和作用(转载)
查看>>
python中全局变量、局部变量、类变量、实例变量简析
查看>>
大众公布量子计算北京交通新一代产品亮相
查看>>
武器加持无人机,远程操控就可以抓获犯罪团伙
查看>>
MySQL数据库迁移
查看>>
IOS应用提交所需的ICON
查看>>
第90届中国电子展聚焦行业新热点,拉动产业链上下游快速发展
查看>>
量子力学多世界解释:这个世界的你是穷光蛋 另一个世界是亿万富翁(文中有赠书活动)...
查看>>
不要小看了互联网智能锁,它正撬动整个多元化居住产品时代!
查看>>
工人小明的新同事
查看>>
OPC UA的安全性分析以及正确使用指南
查看>>
使用树莓派和 projectx/os 托管你自己的电子邮件
查看>>
关于nmonanalyser报错“输入超出文件尾”的解决方法
查看>>