Android实现第三方Mob短信验证登录以及手机号显示和修改用户名(简易新闻 五)

关于之前的功能实现可以从制作简易新闻App导航篇中查看

因为这篇是写了有一段时间的博客,所以这篇(包括后面的简易新闻 六)中关于手机号的传值用的是onActivityResult方法,以及intent.put。。方法,这样写是没有问题的,但是逻辑混乱,所以我在后面针对这一点做了优化,使用了全局变量方法存储,使用手机号这一关键值。如果,你打算一步一步来那也没关系,这样你会对这个app理解的更深入,或者你可以自己考虑一下使用全局变量来传值手机号码。如果你对全局变量用法还不是很明确,你可以参看以下博客:

Android实现存储和实时更新和取出全局变量
好了,讲了这么多先上一下最终效果:

本篇实现功能有:

1. 手机号短信验证登录,建立用户信息数据表
2. 侧滑栏头部显示用户名与手机号
3. 本地记住手机号,方便下次启动时不用重新登录

第一步,建议用户信息表user_info


设置表中id为自增长主键,user_phone外键先不用设置,因为相应功能将在以后实现

关于实现Android连接数据库请看 连接数据库,实现下拉刷新(简易新闻 三)

第二步,修改nav_header.xml文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="180dp"android:padding="10dp"android:orientation="horizontal"android:background="#80FFFF"><de.hdodenhof.circleimageview.CircleImageViewandroid:id="@+id/icon_image"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@mipmap/mouse"android:layout_centerInParent="true"/><TextViewandroid:id="@+id/text_huoqu"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:textColor="@color/colorBlack"android:textSize="14sp"tools:ignore="HardcodedText" /><TextViewandroid:id="@+id/text_username"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_above="@id/text_huoqu"android:layout_marginBottom="9dp"android:layout_toEndOf="@+id/text_huoqu"android:text="个人博客地址:https://blog.csdn.net/Tobey_r1"android:textColor="@color/colorBlack"android:textSize="14sp"tools:ignore="HardcodedText"android:layout_toRightOf="@+id/text_huoqu" />
</RelativeLayout>

第三步,新建一个登录Activity活动LoginActivity.class与activity_main.xml

修改activity_main.xml布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".UserMode.LoginActivity"><de.hdodenhof.circleimageview.CircleImageViewandroid:layout_width="wrap_content"android:id="@+id/imageLogo"android:layout_height="wrap_content"android:layout_alignParentTop="true"android:src="@mipmap/ic_launcher_foreground"android:layout_centerInParent="true"/>
//图片来源选择自己喜欢的图片放入即可<TextViewandroid:id="@+id/textview_login"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/imageLogo"android:layout_marginTop="40dp"android:text="手机号快速登陆"android:textStyle="bold" /><EditTextandroid:id="@+id/login_input_phone_et"android:layout_width="280dp"android:layout_height="wrap_content"android:layout_below="@+id/textview_login"android:layout_marginTop="28dp"android:ems="10"android:hint="请输入手机号"android:inputType="phone" /><requestFocus /><EditTextandroid:id="@+id/login_input_code_et"android:layout_width="170dp"android:layout_height="wrap_content"android:layout_alignLeft="@+id/login_input_phone_et"android:layout_below="@+id/login_input_phone_et"android:layout_marginTop="30dp"android:hint="请输入验证码"android:inputType="textPassword"></EditText><Buttonandroid:id="@+id/login_request_code_btn"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignRight="@+id/login_input_phone_et"android:layout_alignTop="@+id/login_input_code_et"android:background="#01000000"android:text="获取验证码" /><Buttonandroid:id="@+id/login_commit_btn"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignLeft="@+id/login_input_code_et"android:layout_below="@+id/login_input_code_et"android:backgroundTint="@color/colorpink"android:textColor="@color/colorhuise"android:layout_marginTop="5dp"android:text="开始使用" /><Buttonandroid:id="@+id/btn_relogin"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/login_input_code_et"android:layout_alignEnd="@+id/login_input_phone_et"android:layout_alignRight="@id/login_request_code_btn"android:layout_marginTop="65dp"android:layout_marginEnd="-88dp"android:layout_marginRight="-88dp"android:background="#01000000"android:text="手机号注册"android:textStyle="bold" /></RelativeLayout>

如果你是直接从这篇看的话,关于圆形图片的引用加入:

implementation 'de.hdodenhof:circleimageview:2.1.0'

第四步,修改colors.xml文件

在res/values/ 下修改colors.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<resources><color name="colorPrimary">#008577</color><color name="colorPrimaryDark">#00574B</color><color name="colorAccent">#D81B60</color><color name="colorRed">#F00</color><color name="colorBlack">#000</color><color name="colorWhite">#FFF</color><color name="colorhuise">#DCDCDC</color><color name="colorpink">#FF7F50</color>
</resources>

UI效果预览图:

第五步,引入第三步Mob短信验证服务

首先进入Mob平台,选择SMSSDK开始使用:

当然了,你先要注册一个帐号
然后我们创建一个新应用,这里名字就叫简易新闻:

然后会出现一个新的界面,这里会出现我们后面要用的AppKey与AppSecret,每个人的都不一样,选择添加SMSSDK服务:

点击添加之后,我们需要把这个服务添加到我们自己的模块中,我们在下载页面,选择SMSSDK进行下载:

按照上面说明,首先在project的根目录build.gradle中添加(注意不是你的项目中添加):

// Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript {repositories {google()jcenter()}repositories {maven {url "http://mvn.mob.com/android"}}dependencies {classpath 'com.android.tools.build:gradle:3.2.0'classpath 'com.mob.sdk:MobSDK:2018.0319.1724'// NOTE: Do not place your application dependencies here; they belong// in the individual module build.gradle files}
}allprojects {repositories {google()jcenter()}
}task clean(type: Delete) {delete rootProject.buildDir
}

然后修改你的项目Moudle中的build.gradle文件:

apply plugin: 'com.android.application'
apply plugin: 'com.mob.sdk'
android {compileSdkVersion 28MobSDK {appKey "2b85a17d997b2"appSecret "bc386e05d6171e915f1195858a9d017b"SMSSDK {}}defaultConfig {applicationId "com.example.frametest"minSdkVersion 16targetSdkVersion 28versionCode 1versionName "1.0"testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"vectorDrawables.useSupportLibrary = true}buildTypes {release {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'}}}

到这里,我们就可以通过代码来实现短信验证啦。

第六步,实现登录与用户信息存储

修改LoginActivity.class

package com.example.frametest.UserMode;import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.frametest.R;
import com.example.frametest.tools.DBOpenHelper;
import com.mob.MobSDK;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;public class LoginActivity extends AppCompatActivity implements View.OnClickListener {String APPKEY = "2b85a17d997b2";String APPSECRET = "bc386e05d6171e915f1195858a9d017b";String phoneNums;// 手机号输入框private EditText inputPhoneEt;private static final int UPDATE_INSERT = 0;// 验证码输入框private EditText inputCodeEt;// 获取验证码按钮private Button requestCodeBtn;// 注册按钮private Button commitBtn;private Button shareBtn;//倒计时显示   可以手动更改。int i = 50;String inputText;@SuppressLint("HandlerLeak")private Handler userHandler = new Handler(){@Overridepublic void handleMessage(Message msg) {String user_phone,user_name,user_pasw;switch (msg.what){case UPDATE_INSERT:User user = (User) msg.obj;user_phone = user.getUser_phone();break;}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_login);inputPhoneEt = (EditText) findViewById(R.id.login_input_phone_et);inputCodeEt = (EditText) findViewById(R.id.login_input_code_et);requestCodeBtn = (Button) findViewById(R.id.login_request_code_btn);commitBtn = (Button) findViewById(R.id.login_commit_btn);// 初始化sdkMobSDK.init(this,APPKEY,APPSECRET);}@Overrideprotected void onStart() {super.onStart();requestCodeBtn.setOnClickListener(this);commitBtn.setOnClickListener(this);//启动短信验证SDKEventHandler eventHandler = new EventHandler(){@Overridepublic void afterEvent(int event, int result, Object data) {Message msg = new Message();msg.arg1 = event;msg.arg2 = result;msg.obj = data;handler.sendMessage(msg);}};//注册回调监听接口SMSSDK.registerEventHandler(eventHandler);}@Overridepublic void onClick(View v) {//取出输入的手机号phoneNums = inputPhoneEt.getText().toString();switch (v.getId()) {case R.id.login_request_code_btn:// 1. 判断手机号是不是11位并且看格式是否合理if (!judgePhoneNums(phoneNums)) {return;} // 2. 通过sdk发送短信验证SMSSDK.getVerificationCode("86", phoneNums);// 3. 把按钮变成不可点击,并且显示倒计时(正在获取)requestCodeBtn.setClickable(false);requestCodeBtn.setText("重新发送(" + i + ")");new Thread(new Runnable() {@Overridepublic void run() {for (; i > 0; i--) {handler.sendEmptyMessage(-9);if (i <= 0) {break;}try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}handler.sendEmptyMessage(-8);}}).start();break;case R.id.login_commit_btn://将收到的验证码和手机号提交再次核对SMSSDK.submitVerificationCode("86", phoneNums, inputCodeEt.getText().toString());//将获取的登录的手机号存储进user_info数据表中new Thread(new Runnable() {@Overridepublic void run() {Connection conn = null;conn = (Connection) DBOpenHelper.getConn();String sql = "insert into user_info(user_phone) values(?)";int i = 0;String id=null;String user_name=null;String user_phone=null;String user_pasw=null;PreparedStatement pstmt;try {User user = new User();pstmt = (PreparedStatement) conn.prepareStatement(sql);pstmt.setString(1,phoneNums);i = pstmt.executeUpdate();user.setUser_phone(user_phone);Message message = new Message();message.what = UPDATE_INSERT;message.obj = user;userHandler.sendMessage(message);pstmt.close();conn.close();} catch (SQLException e) {e.printStackTrace();}}}).start();break;}}@SuppressLint("HandlerLeak")Handler handler = new Handler(){public void handleMessage(Message msg) {if (msg.what == -9) {requestCodeBtn.setText("重新发送(" + i + ")");} else if (msg.what == -8) {requestCodeBtn.setText("获取验证码");requestCodeBtn.setClickable(true);i = 30;} else {int event = msg.arg1;int result = msg.arg2;Object data = msg.obj;Log.e("event", "event=" + event);if (result == SMSSDK.RESULT_COMPLETE) {// 短信注册成功后,返回MainActivity,然后提示if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功Toast.makeText(getApplicationContext(), "提交验证码成功",Toast.LENGTH_SHORT).show();Intent intent = new Intent();intent.putExtra("data_return",inputPhoneEt.getText().toString());setResult(RESULT_OK,intent);Bundle bundle = new Bundle();bundle.putString("userName",phoneNums);intent.putExtras(bundle);finish();} else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {Toast.makeText(getApplicationContext(), "正在获取验证码",Toast.LENGTH_SHORT).show();} else {Toast.makeText(LoginActivity.this,"验证码不正确",Toast.LENGTH_SHORT).show();((Throwable) data).printStackTrace();}}}}};/*** 判断手机号码是否合理** @param phoneNums*/private boolean judgePhoneNums(String phoneNums) {if (isMatchLength(phoneNums, 11)&& isMobileNO(phoneNums)) {return true;}Toast.makeText(this, "手机号码输入有误!",Toast.LENGTH_SHORT).show();return false;}/*** 验证手机格式*/private boolean isMobileNO(String mobileNums) {/** 移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188* 联通:130、131、132、152、155、156、185、186 电信:133、153、180、189、(1349卫通)* 总结起来就是第一位必定为1,第二位必定为3或5或8,其他位置的可以为0-9*/String telRegex = "[1][358]\\d{9}";// "[1]"代表第1位为数字1,"[358]"代表第二位可以为3、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。if (TextUtils.isEmpty(mobileNums))return false;elsereturn mobileNums.matches(telRegex);}/*** 判断一个字符串的位数* @param str* @param length* @return*/private boolean isMatchLength(String str, int length) {if (str.isEmpty()) {return false;} else {return str.length() == length ? true : false;}}@Overrideprotected void onDestroy() {//反注册回调监听接口SMSSDK.unregisterAllEventHandler();//存储手机号inputText = inputPhoneEt.getText().toString();save(inputText);System.out.println("活动毁灭之前是否传值"+inputText);super.onDestroy();}public void save(String inputText) {FileOutputStream out = null;BufferedWriter writer = null;try {out = openFileOutput("data",Context.MODE_PRIVATE);writer = new BufferedWriter(new OutputStreamWriter(out));writer.write(inputText);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (writer != null){try {writer.close();} catch (IOException e) {e.printStackTrace();}}}}
}

第七步,new一个User类为表user_info存储使用

package com.example.frametest.UserMode;public class User {private int id;private String user_name;private String user_phone;private String user_pasw;private int user_age;private boolean user_sex;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUser_name() {return user_name;}public void setUser_name(String user_name) {this.user_name = user_name;}public String getUser_phone() {return user_phone;}public void setUser_phone(String user_phone) {this.user_phone = user_phone;}public String getUser_pasw() {return user_pasw;}public void setUser_pasw(String user_pasw) {this.user_pasw = user_pasw;}public int getUser_age() {return user_age;}public void setUser_age(int user_age) {this.user_age = user_age;}public boolean isUser_sex() {return user_sex;}public void setUser_sex(boolean user_sex) {this.user_sex = user_sex;}
}

第八步修改MainActivity.class

package com.example.frametest;import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.frametest.UserMode.LoginActivity;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;public class MainActivity extends AppCompatActivity {private android.support.v7.widget.Toolbar toolbar;private DrawerLayout mDrawerLayout;private NavigationView navigationView;private TabLayout tabLayout;private ViewPager viewPager;private List<String> list;private TextView tvhuoqu,tvName;String phonenumber;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);toolbar =  findViewById(R.id.toolbar);mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); //获取抽屉布局navigationView = (NavigationView) findViewById(R.id.nav_design);//获取菜单控件实例View v = navigationView.getHeaderView(0);CircleImageView circleImageView =(CircleImageView) v.findViewById(R.id.icon_image);tabLayout = (TabLayout) findViewById(R.id.tabLayout);viewPager = (ViewPager) findViewById(R.id.viewPager);list = new ArrayList<>();tvhuoqu = (TextView) findViewById(R.id.text_huoqu);}@Overrideprotected void onStart() {super.onStart();/* toolbar.setLogo(R.drawable.icon);//设置图片logo,你可以添加自己的图片*/toolbar.setTitle("简易新闻");setSupportActionBar(toolbar);ActionBar actionBar = getSupportActionBar();if (actionBar !=null){//通过HomeAsUp来让导航按钮显示出来actionBar.setDisplayHomeAsUpEnabled(true);//设置Indicator来添加一个点击图标actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_24dp);}navigationView.setCheckedItem(R.id.nav_call);//设置第一个默认选中navigationView.setNavigationItemSelectedListener(new  NavigationView.OnNavigationItemSelectedListener() {//设置菜单项的监听事件@Overridepublic boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {mDrawerLayout.closeDrawers();switch (menuItem.getItemId()) {case R.id.nav_call://每个菜单项的点击事件,通过Intent实现点击item简单实现活动页面的跳转。/*Intent intent = new Intent(MainActivity.this, Main2Activity.class);//第二个Main2Activity.class需要你自己new一个 Activity来做出其他功能页面startActivity(intent);*/break;case R.id.nav_friends:Toast.makeText(MainActivity.this, "你点击了好友", Toast.LENGTH_SHORT).show();break;case R.id.nav_location:Toast.makeText(MainActivity.this, "你点击了发布新闻,下步实现", Toast.LENGTH_SHORT).show();break;case R.id.nav_favorite:Toast.makeText(MainActivity.this, "你点击了个人收藏,下步实现", Toast.LENGTH_SHORT).show();break;case R.id.nav_settings:Toast.makeText(MainActivity.this,"需要做出登出功能,可扩展夜间模式,离线模式等,检查更新",Toast.LENGTH_LONG).show();break;case R.id.nav_exit:Intent intent = new Intent(MainActivity.this,LoginActivity.class);startActivityForResult(intent,1);break;default:}return true;}});list.add("头条");list.add("社会");list.add("国内");list.add("国际");list.add("娱乐");list.add("体育");list.add("军事");list.add("科技");list.add("财经");/* viewPager.setOffscreenPageLimit(1);*/viewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {//得到当前页的标题,也就是设置当前页面显示的标题是tabLayout对应标题@Nullable@Overridepublic CharSequence getPageTitle(int position) {return list.get(position);}@Overridepublic Fragment getItem(int position) {NewsFragment newsFragment = new NewsFragment();//判断所选的标题,进行传值显示Bundle bundle = new Bundle();if (list.get(position).equals("头条")){bundle.putString("name","top");}else if (list.get(position).equals("社会")){bundle.putString("name","shehui");}else if (list.get(position).equals("国内")){bundle.putString("name","guonei");}else if (list.get(position).equals("国际")){bundle.putString("name","guoji");}else if (list.get(position).equals("娱乐")){bundle.putString("name","yule");}else if (list.get(position).equals("体育")){bundle.putString("name","tiyu");}else if (list.get(position).equals("军事")){bundle.putString("name","junshi");}else if (list.get(position).equals("科技")){bundle.putString("name","keji");}else if (list.get(position).equals("财经")){bundle.putString("name","caijing");}else if (list.get(position).equals("时尚")){bundle.putString("name","shishang");}newsFragment.setArguments(bundle);return newsFragment;}@NonNull@Overridepublic Object instantiateItem(@NonNull ViewGroup container, int position) {NewsFragment newsFragment = (NewsFragment)  super.instantiateItem(container, position);return newsFragment;}@Overridepublic int getItemPosition(@NonNull Object object) {return FragmentStatePagerAdapter.POSITION_NONE;}@Overridepublic int getCount() {return list.size();}});//TabLayout要与ViewPAger关联显示tabLayout.setupWithViewPager(viewPager);String inputText = load();if (!TextUtils.isEmpty(inputText)){//取出之前的手机号phonenumber =inputText;}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {//获取toolbar菜单项getMenuInflater().inflate(R.menu.toolbar,menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {switch (item.getItemId()){//R.id.home修改导航按钮的点击事件为打开侧滑栏case android.R.id.home:mDrawerLayout.openDrawer(GravityCompat.START);  //打开侧滑栏tvhuoqu = (TextView) findViewById(R.id.text_huoqu);tvhuoqu.setText(phonenumber);//打开侧滑栏的时候显示手机号,下步预计实现查询用户名break;case R.id.userFeedback:final EditText ed =new EditText(MainActivity.this);AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);dialog.setTitle("用户反馈");dialog.setView(ed);dialog.setCancelable(false);dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {//添加点击事件}});dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {}});dialog.show();break;case R.id.userExit:Toast.makeText(this,"ni click 退出",Toast.LENGTH_SHORT).show();break;default:}return true;}@Overrideprotected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {switch (requestCode){case 1:if (resultCode == RESULT_OK){//根据resultcode来判断是哪个页面的返回值String returnedData = data.getStringExtra("data_return");phonenumber = returnedData;View v = navigationView.getHeaderView(0);tvhuoqu = (TextView) v.findViewById(R.id.text_huoqu);tvhuoqu.setText(phonenumber);System.out.println("*********");System.out.println("*********");System.out.println("手机号获取到的内容+"+phonenumber);}break;default:}}public String load() {//读取我们之前存储到data文件中的手机号,方便下次启动app时直接使用FileInputStream in = null;BufferedReader reader = null;StringBuilder content = new StringBuilder();try {in = openFileInput("data");System.out.println("是否读到文件内容"+in);reader = new BufferedReader(new InputStreamReader(in));String line = "";while ((line = reader.readLine()) != null){content.append(line);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {if (reader != null){try {reader.close();} catch (IOException e) {e.printStackTrace();}}}return content.toString();}
}

第九步,修改AndroidManifest.xml文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.frametest"><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><!-- mob发送短信权限 --><uses-permission android:name="android.permission.READ_CONTACTS" /><uses-permission android:name="android.permission.READ_PHONE_STATE" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.RECEIVE_SMS" /><uses-permission android:name="android.permission.READ_SMS" /><uses-permission android:name="android.permission.GET_TASKS" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><activity android:name=".WebActivity" /><activity android:name=".UserMode.LoginActivity"></activity></application></manifest>

此时我们先看一下运行后的效果:


还可以在Mob查看我们短信验证记录:

此时我们还没有实现用户修改用户名的功能。

实现第一步,修改nav_header.xml布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="180dp"android:padding="10dp"android:orientation="horizontal"android:background="#80FFFF"><de.hdodenhof.circleimageview.CircleImageViewandroid:id="@+id/icon_image"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@mipmap/mouse"android:layout_centerInParent="true"/><TextViewandroid:id="@+id/text_huoqu"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:textColor="@color/colorBlack"android:textSize="14sp"tools:ignore="HardcodedText" /><TextViewandroid:id="@+id/text_username"android:layout_above="@id/text_huoqu"android:textColor="@color/colorBlack"android:textSize="14sp"android:layout_width="wrap_content"android:layout_height="wrap_content"tools:ignore="HardcodedText"android:text="个人博客地址:https://blog.csdn.net/Tobey_r1"android:layout_toRightOf="@+id/text_huoqu" />
</RelativeLayout>

第二步,给侧滑栏编辑资料按钮添加点击事件

修改MainActivity.class:

package com.example.frametest;import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;import com.example.frametest.UserMode.LoginActivity;
import com.example.frametest.UserMode.User;
import com.example.frametest.UserMode.User_DataActivity;
import com.example.frametest.tools.DBOpenHelper;import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;public class MainActivity extends AppCompatActivity {private android.support.v7.widget.Toolbar toolbar;private DrawerLayout mDrawerLayout;private NavigationView navigationView;private TabLayout tabLayout;private ViewPager viewPager;private List<String> list;private TextView tvhuoqu,tvName;String phonenumber,userName;private static final int USER_LOOK_NAME = 0;@SuppressLint("HandlerLeak")private Handler userFeedHandler = new Handler(){@Overridepublic void handleMessage(Message msg) {String admin_title,admin_url,user_name;switch (msg.what){case USER_LOOK_NAME:User user = (User) msg.obj;user_name =user.getUser_name();tvName = (TextView) findViewById(R.id.text_username);tvName.setText(user_name);break;}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);toolbar =  findViewById(R.id.toolbar);mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); //获取抽屉布局navigationView = (NavigationView) findViewById(R.id.nav_design);//获取菜单控件实例View v = navigationView.getHeaderView(0);CircleImageView circleImageView =(CircleImageView) v.findViewById(R.id.icon_image);tabLayout = (TabLayout) findViewById(R.id.tabLayout);viewPager = (ViewPager) findViewById(R.id.viewPager);list = new ArrayList<>();tvhuoqu = (TextView) findViewById(R.id.text_huoqu);}@Overrideprotected void onStart() {super.onStart();/* toolbar.setLogo(R.drawable.icon);//设置图片logo,你可以添加自己的图片*/toolbar.setTitle("简易新闻");setSupportActionBar(toolbar);ActionBar actionBar = getSupportActionBar();if (actionBar !=null){//通过HomeAsUp来让导航按钮显示出来actionBar.setDisplayHomeAsUpEnabled(true);//设置Indicator来添加一个点击图标actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_24dp);}navigationView.setCheckedItem(R.id.nav_call);//设置第一个默认选中navigationView.setNavigationItemSelectedListener(new  NavigationView.OnNavigationItemSelectedListener() {//设置菜单项的监听事件@Overridepublic boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {mDrawerLayout.closeDrawers();switch (menuItem.getItemId()) {case R.id.nav_call://通过判断手机号是否存在,来决定是进入编辑资料页面还是进入登陆页面if (phonenumber != null){Intent unIntent = new Intent(MainActivity.this,User_DataActivity.class);unIntent.putExtra("user_settings",phonenumber);startActivityForResult(unIntent,3);} else {Intent exitIntent = new Intent(MainActivity.this,LoginActivity.class);startActivityForResult(exitIntent,2);}break;case R.id.nav_friends:Toast.makeText(MainActivity.this, "你点击了好友", Toast.LENGTH_SHORT).show();break;case R.id.nav_location:Toast.makeText(MainActivity.this, "你点击了发布新闻,下步实现", Toast.LENGTH_SHORT).show();break;case R.id.nav_favorite:Toast.makeText(MainActivity.this, "你点击了个人收藏,下步实现", Toast.LENGTH_SHORT).show();break;case R.id.nav_settings:Toast.makeText(MainActivity.this,"需要做出登出功能,可扩展夜间模式,离线模式等,检查更新",Toast.LENGTH_LONG).show();break;case R.id.nav_exit:Intent intent = new Intent(MainActivity.this,LoginActivity.class);startActivityForResult(intent,1);break;default:}return true;}});list.add("头条");list.add("社会");list.add("国内");list.add("国际");list.add("娱乐");list.add("体育");list.add("军事");list.add("科技");list.add("财经");/* viewPager.setOffscreenPageLimit(1);*/viewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {//得到当前页的标题,也就是设置当前页面显示的标题是tabLayout对应标题@Nullable@Overridepublic CharSequence getPageTitle(int position) {return list.get(position);}@Overridepublic Fragment getItem(int position) {NewsFragment newsFragment = new NewsFragment();//判断所选的标题,进行传值显示Bundle bundle = new Bundle();if (list.get(position).equals("头条")){bundle.putString("name","top");}else if (list.get(position).equals("社会")){bundle.putString("name","shehui");}else if (list.get(position).equals("国内")){bundle.putString("name","guonei");}else if (list.get(position).equals("国际")){bundle.putString("name","guoji");}else if (list.get(position).equals("娱乐")){bundle.putString("name","yule");}else if (list.get(position).equals("体育")){bundle.putString("name","tiyu");}else if (list.get(position).equals("军事")){bundle.putString("name","junshi");}else if (list.get(position).equals("科技")){bundle.putString("name","keji");}else if (list.get(position).equals("财经")){bundle.putString("name","caijing");}else if (list.get(position).equals("时尚")){bundle.putString("name","shishang");}newsFragment.setArguments(bundle);return newsFragment;}@NonNull@Overridepublic Object instantiateItem(@NonNull ViewGroup container, int position) {NewsFragment newsFragment = (NewsFragment)  super.instantiateItem(container, position);return newsFragment;}@Overridepublic int getItemPosition(@NonNull Object object) {return FragmentStatePagerAdapter.POSITION_NONE;}@Overridepublic int getCount() {return list.size();}});//TabLayout要与ViewPAger关联显示tabLayout.setupWithViewPager(viewPager);String inputText = load();if (!TextUtils.isEmpty(inputText)){phonenumber =inputText;}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {//获取toolbar菜单项getMenuInflater().inflate(R.menu.toolbar,menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {switch (item.getItemId()){//R.id.home修改导航按钮的点击事件为打开侧滑栏case android.R.id.home:mDrawerLayout.openDrawer(GravityCompat.START);  //打开侧滑栏tvhuoqu = (TextView) findViewById(R.id.text_huoqu);tvhuoqu.setText(phonenumber);//用户开启侧滑栏时,查询数据库对应手机号的用户名,并显示在侧滑栏头部new Thread(new Runnable() {@Overridepublic void run() {Connection conn = null;conn = (Connection) DBOpenHelper.getConn();String sql = "select user_name from user_info where  user_phone ='"+phonenumber+"'";Statement pstmt;try {pstmt = (Statement) conn.createStatement();ResultSet rs = pstmt.executeQuery(sql);while (rs.next()){User user = new User();user.setUser_name(rs.getString(1));Message msg = new Message();msg.what=USER_LOOK_NAME;msg.obj = user;userFeedHandler.sendMessage(msg);}pstmt.close();conn.close();} catch (SQLException e) {e.printStackTrace();}}}).start();break;case R.id.userFeedback:final EditText ed =new EditText(MainActivity.this);AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);dialog.setTitle("用户反馈");dialog.setView(ed);dialog.setCancelable(false);dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {//添加点击事件}});dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {}});dialog.show();break;case R.id.userExit:Toast.makeText(this,"ni click 退出",Toast.LENGTH_SHORT).show();break;default:}return true;}@Overrideprotected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {switch (requestCode){case 1:if (resultCode == RESULT_OK){String returnedData = data.getStringExtra("data_return");phonenumber = returnedData;View v = navigationView.getHeaderView(0);tvhuoqu = (TextView) v.findViewById(R.id.text_huoqu);tvhuoqu.setText(phonenumber);System.out.println("*********");System.out.println("*********");System.out.println("手机号获取到的内容+"+phonenumber);}break;case 2:if(resultCode == RESULT_OK){String returnedData = data.getStringExtra("data_return");phonenumber = returnedData;}break;case 3:if (requestCode == RESULT_OK){String retutnName = data.getStringExtra("return_name");userName = retutnName;}break;default:}}public String load() {FileInputStream in = null;BufferedReader reader = null;StringBuilder content = new StringBuilder();try {in = openFileInput("data");System.out.println("是否读到文件内容"+in);reader = new BufferedReader(new InputStreamReader(in));String line = "";while ((line = reader.readLine()) != null){content.append(line);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {if (reader != null){try {reader.close();} catch (IOException e) {e.printStackTrace();}}}return content.toString();}
}

第三步,添加点击事件对应的活动

new一个新的activity,User_DataActivity.class与activity_user_data.xml

activity_user_data.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".UserMode.User_DataActivity"><LinearLayoutandroid:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"><android.support.v7.widget.Toolbarandroid:id="@+id/userData_toolbar"android:layout_width="match_parent"android:layout_height="?attr/actionBarSize"app:titleTextColor="@color/black"android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"android:background="@color/colorBackground"app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/><LinearLayoutandroid:orientation="horizontal"android:background="@color/jinse"android:layout_width="match_parent"android:layout_height="wrap_content"><TextViewandroid:id="@+id/tv_user_photo"android:layout_width="300dp"android:layout_height="match_parent"android:background="#01000000"android:gravity="center_vertical"android:clickable="true"android:text="头像"android:textStyle="bold" /><ImageViewandroid:id="@+id/imageView_user"android:layout_width="55dp"android:background="#01000000"android:layout_height="55dp"/></LinearLayout><LinearLayoutandroid:layout_marginTop="15dp"android:orientation="horizontal"android:background="@color/jinse"android:layout_width="match_parent"android:layout_height="wrap_content"><TextViewandroid:id="@+id/tv_nc"android:layout_width="match_parent"android:layout_height="55dp"android:layout_gravity="center_horizontal"android:layout_weight="1"android:clickable="true"android:background="#01000000"android:gravity="center_vertical"android:text="用户名"android:textStyle="bold" /><TextViewandroid:id="@+id/tv_nc_fb"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="2"android:background="#01000000"android:gravity="center_vertical" /></LinearLayout><LinearLayoutandroid:orientation="horizontal"android:layout_marginTop="15dp"android:background="@color/jinse"android:layout_width="match_parent"android:layout_height="wrap_content"><TextViewandroid:id="@+id/tv_xingbie"android:layout_width="match_parent"android:layout_height="55dp"android:layout_weight="1"android:background="#01000000"android:gravity="center_vertical"android:text="性别"android:textStyle="bold" /><TextViewandroid:id="@+id/tv_xinbie_fb"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="3"android:background="#01000000"android:gravity="center_vertical"/></LinearLayout><LinearLayoutandroid:layout_marginTop="15dp"android:orientation="horizontal"android:background="@color/jinse"android:layout_width="match_parent"android:layout_height="wrap_content"><TextViewandroid:id="@+id/tv_nianlin"android:layout_width="match_parent"android:layout_height="55dp"android:layout_weight="1"android:background="#01000000"android:gravity="center_vertical"android:text="年龄"android:textStyle="bold" /><TextViewandroid:id="@+id/tv_nianlin_fb"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="3"android:background="#01000000"android:gravity="center_vertical"/></LinearLayout></LinearLayout></android.support.design.widget.CoordinatorLayout>

修改color.xml:

<color name="colorpink">#FF7F50</color><color name="colorBackground">#ffffff</color><color name="jinse">#FFD700</color>

User_DataActivity.class:

package com.example.frametest.UserMode;import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;import com.example.frametest.R;
import com.example.frametest.tools.DBOpenHelper;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;public class User_DataActivity extends AppCompatActivity {private ImageView imageView_user;public static final int CHOOSE_USER_TOUX =11;public static final int USER_SETTINGS_NAME =12;public static final int USER_UPDATE_NAME =13;private TextView tv_user_photo,tv_nc,tv_nc_fb;String user_setting_phone;String input_userName;@SuppressLint("HandlerLeak")private Handler userSettingsHandler = new Handler(){@Overridepublic void handleMessage(Message msg) {String admin_title,admin_url;switch (msg.what){case USER_SETTINGS_NAME:Toast.makeText(User_DataActivity.this,"用户名为空或不存在!",Toast.LENGTH_SHORT).show();break;case USER_UPDATE_NAME:tv_nc_fb.setText(input_userName);break;}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_user__data);user_setting_phone = getIntent().getStringExtra("user_settings");Toolbar uToolbar = (Toolbar) findViewById(R.id.userData_toolbar);tv_user_photo = (TextView)findViewById(R.id.tv_user_photo);imageView_user = (ImageView)findViewById(R.id.imageView_user);tv_nc = (TextView)findViewById(R.id.tv_nc);tv_nc_fb = (TextView) findViewById(R.id.tv_nc_fb);uToolbar.setTitle("个人信息");setSupportActionBar(uToolbar);ActionBar actionBar = getSupportActionBar();if (actionBar != null){actionBar.setDisplayHomeAsUpEnabled(true);actionBar.setHomeAsUpIndicator(R.drawable.ic_chevron_left);}}@Overrideprotected void onStart() {super.onStart();tv_user_photo.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {if (ContextCompat.checkSelfPermission(User_DataActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE) !=PackageManager.PERMISSION_GRANTED){ActivityCompat.requestPermissions(User_DataActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);}else {openAlbum();}}});tv_nc.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {final EditText editText =new EditText(User_DataActivity.this);AlertDialog.Builder alog = new AlertDialog.Builder(User_DataActivity.this);alog.setTitle("输入用户名");alog.setView(editText);alog.setCancelable(false);alog.setPositiveButton("提交", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {new Thread(new Runnable() {@Overridepublic void run() {input_userName = editText.getText().toString();   //对修改用户名是否为空或“ ”进行判断                          if ("".equals(input_userName) || input_userName == null) {//是空就通过handler发送message提示Message msg = new Message();msg.what =USER_SETTINGS_NAME;userSettingsHandler.sendMessage(msg);} else {//不是空就插入到数据库中Connection conn = null;conn = (Connection) DBOpenHelper.getConn();String sql = "update user_info set user_name='"+input_userName+"' where user_phone='"+user_setting_phone+"'";int i = 0;PreparedStatement pstmt;try {pstmt = (PreparedStatement) conn.prepareStatement(sql);i = pstmt.executeUpdate();pstmt.close();conn.close();Message msg = new Message();msg.what = USER_UPDATE_NAME;userSettingsHandler.sendMessage(msg);} catch (SQLException e) {e.printStackTrace();}}}}).start();}});alog.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {}});alog.show();}});}private void openAlbum() {Intent mIntent = new Intent("android.intent.action.GET_CONTENT");mIntent.setType("image/*");startActivityForResult(mIntent,CHOOSE_USER_TOUX);}@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {switch (requestCode){case 1:if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){openAlbum();}else {Toast.makeText(this,"you denied the permission",Toast.LENGTH_SHORT).show();}break;default:}}@Overrideprotected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {switch (requestCode){case CHOOSE_USER_TOUX:if (resultCode == RESULT_OK) {if (Build.VERSION.SDK_INT >= 19){handleImageOnKiKat(data);}else {handleImageBeforeKiKat(data);}}break;}}@TargetApi(Build.VERSION_CODES.KITKAT)private void handleImageOnKiKat(Intent data) {String imagePath = null;Uri uri = data.getData();if (DocumentsContract.isDocumentUri(this,uri)){String docId = DocumentsContract.getDocumentId(uri);if ("com.android.providers.media.documents".equals(uri.getAuthority())){String id = docId.split(":")[1];String selection = MediaStore.Images.Media._ID + "=" + id;imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);}else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));imagePath = getImagePath(contentUri,null);}} else if ("content".equalsIgnoreCase(uri.getScheme())){//如或是content类型的URI就使用普通方法处理imagePath = getImagePath(uri,null);} else if ("file".equalsIgnoreCase(uri.getScheme())){//如果是file类型的直接获取图片路径就行imagePath = uri.getPath();}diplayImage(imagePath); //根据路径显示图片}private void handleImageBeforeKiKat(Intent data) {Uri uri = data.getData();String imagePath = getImagePath(uri,null);diplayImage(imagePath);}private String getImagePath(Uri uri, String selection) {String path = null;//通过Uri和selection来获取真实的图片路径Cursor cursor = getContentResolver().query(uri,null,selection,null,null);if (cursor != null){if (cursor.moveToFirst()){path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));}cursor.close();}return path;}private void diplayImage(String imagePath) {if (imagePath != null){Bitmap bitmap = BitmapFactory.decodeFile(imagePath);imageView_user.setImageBitmap(bitmap);int a =10;} else {Toast.makeText(this,"failed to get image",Toast.LENGTH_SHORT).show();}}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {switch (item.getItemId()){case android.R.id.home:User_DataActivity.this.finish();break;}return true;}@Overrideprotected void onDestroy() {super.onDestroy();Intent intent = new Intent();intent.putExtra("return_name",input_userName);setResult(RESULT_OK,intent);finish();}
}

到此,本篇功能已全部实现:
最终实现效果如下:

欢迎各位一起讨论。
下篇将会实现用户收藏新闻,以及查看个人收藏功能。
Android app实现用户收藏新闻以及查看新闻(简易新闻 六)
项目源码GitHub地址为:https://github.com/ziruiliu1/MyBlog
源码中已经优化了手机号存储与使用。

Android实现第三方Mob短信验证登录以及手机号显示和修改用户名(简易新闻 五)相关推荐

  1. Mob短信验证码登录(Android)

    提示:站在巨人肩膀上的小白,大家可以提出自己的看法.如有侵删: 原文参考链接: https://blog.csdn.net/qq_52139206/article/details/124552348 ...

  2. Vue与Node.js实现手机短信验证登录

    手机短信使用的第三方平台是联容云,注册就送8块钱体验费,足够自己用用了,注册完自己建一个应用就能拿到需要使用的配置了,如图 注册完之后1就可以使用了. Node.js后端使用了Express框架 &q ...

  3. 七丶青龙nvjdc部署教程+短信验证登录对接傻妞

    青龙nvjdc部署教程+短信验证登录对接傻妞Nolanjdc 没有服务器的先自行购买,这里推荐腾讯云2H4G8M首年70–点击购买 青龙面板安装教程 傻妞机器人安装教程 XDD安装教程 QQ交流:10 ...

  4. 工厂如何实现无线wifi短信验证登录?工厂上网实名认证系统

    工厂如何实现无线wifi短信验证登录?工厂上网实名认证系统 工厂提供公共的无线wifi上网服务,需对用户进行实名认证.手机短信实名认证以其用户体验.综合成本等优势,成为工厂无线上网认证的首选方案. 一 ...

  5. Spring boot短信验证登录

    一.短信验证码业务 我用的是第三平台的短信服务,当用户点击发送验证码,会调用短信平台接口,从而给手机发验证码.流程如下: c 首先需要工具类,来发送验证码 public class DXMessage ...

  6. 秒滴云短信验证登录小demo

    短信验证登录demo <a class="click_login_head" data-href="/member" data-method=" ...

  7. Springboot实现短信验证登录

    一.介绍 使用短信验证登录也是现在实际项目中普遍使用的一种登录, 二.实际的操作流程 1.用户在前端页面输入手机号码之后,点击发送验证码 2.前端将手机号传给后端 3.后端生成一个6为的随机数通过短信 ...

  8. java WEB调用秒嘀科技短信验证接口(实现短信验证登录)

    java WEB调用秒嘀科技短信验证接口(实现短信验证登录) 前言 注册秒嘀云账号 登录秒嘀云官网 代码 前言 短信验证登咱就不多说了,为什么推荐用秒嘀的呢,应为他会送你10元钱,对于新手来说10元钱 ...

  9. 014_关于session实现短信验证登录的前端启动

    014_关于session实现短信验证登录的前端启动 1.进入到nginx相对应的文件夹,shfit+右键,进入PowerShell并且执行nginx 2.启动我们的nginx,嘿嘿,可以访问我们的前 ...

最新文章

  1. python json文件_python读写json文件的简单实现
  2. 如何通过Gradle上传Android库到JCenter
  3. 克服游戏运营中IB的长尾挑战
  4. 【c++】映射表std::map
  5. hdu_1358Period(kmp找循环前缀)
  6. [Python] 制作启动uiautomator2 的web版 uiautomatorviewer2 批处理启动
  7. 面试官问我:解释一下Dubbo服务暴露
  8. cydia源_Cydia常见错误提示(红字/黄字)
  9. java短信验证码实现_社交APP开发短信验证是通过什么技术实现
  10. sqlmap能测试java么_ibatis框架如何测试?ibatis入门解析
  11. 通过matlab实现正交表
  12. 卡巴斯基 7.0 免费激活码使用方法!
  13. android商店账号密码错误,android app 自定义签名出现错误:Keystore was tampered with, or password was incorrect...
  14. 手机厂商“卷”到了手腕上
  15. SWUST OJ 954单链表的链接
  16. html页面转成PDF,PDF下载
  17. ntohs, ntohl, htons,htonl inet_aton等详解
  18. 扫盲加扯淡——网友随笔画之云计算
  19. 本经阴符七术——盛神法五龙
  20. 二维码的接口开发(从入门到使用)

热门文章

  1. 一条调整的消息(第15期)
  2. 扑克牌接龙游戏代码c语言,C++点扑克牌游戏(含源码).doc
  3. python一行代码完成正态分布检验,附原理详解
  4. 搭建keil开发环境,完成一个基于STM32汇编程序的编写
  5. EL与JSTL使用介绍
  6. Impinj携手英特尔推出EPC UHF RFID平台,助力解决方案快速开发
  7. idea替换所有文件中的内容
  8. 重置目录服务还原模式管理员密码
  9. 智慧物流之电子标签在RFID仓库管理系统中的应用-RFID仓库智能盘点
  10. 火车轨道铁路轨道检测识别(附带Python源码+详细解析)