1.AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.glsite.qqloginweb"><uses-permission android:name="android.permission.INTERNET"/><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"android:networkSecurityConfig="@xml/network_security_config"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

2.QQLoginWeb\app\src\main\res\xml\network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config><base-config cleartextTrafficPermitted="true" /></network-security-config>

3.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".MainActivity"><ImageViewandroid:id="@+id/iv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginStart="8dp"android:layout_marginLeft="8dp"android:layout_marginTop="60dp"android:layout_marginEnd="8dp"android:layout_marginRight="8dp"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent"app:srcCompat="@mipmap/ic_launcher" /><Buttonandroid:id="@+id/bt_login"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginStart="8dp"android:layout_marginLeft="8dp"android:layout_marginTop="36dp"android:layout_marginEnd="8dp"android:layout_marginRight="8dp"android:text="登录"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/cb_remember" /><EditTextandroid:id="@+id/et_number"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginStart="8dp"android:layout_marginLeft="8dp"android:layout_marginTop="32dp"android:layout_marginEnd="8dp"android:layout_marginRight="8dp"android:ems="10"android:hint="请输入您的账号"android:inputType="textPersonName"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintHorizontal_bias="0.503"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/iv" /><EditTextandroid:id="@+id/et_password"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginStart="8dp"android:layout_marginLeft="8dp"android:layout_marginTop="8dp"android:layout_marginEnd="8dp"android:layout_marginRight="8dp"android:ems="10"android:hint="请输入您的密码"android:inputType="textPassword"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/et_number" /><CheckBoxandroid:id="@+id/cb_remember"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginStart="8dp"android:layout_marginLeft="8dp"android:layout_marginTop="52dp"android:layout_marginEnd="8dp"android:layout_marginRight="8dp"android:text="记住用户名和密码"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/et_password" />
</android.support.constraint.ConstraintLayout>

4.MainActivity.java

package com.glsite.qqloginweb;import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;public class MainActivity extends AppCompatActivity implements View.OnClickListener {private static final int STATUS_SUCCESS = 1;private static final int STATUS_ERROR = 2;private EditText mEtNumber;private EditText mEtPassword;private CheckBox mCbRemember;private Button mBtLogin;private SharedPreferences mSp;private Handler mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case STATUS_SUCCESS:Toast.makeText(MainActivity.this, (String)msg.obj, Toast.LENGTH_SHORT).show();break;case STATUS_ERROR:Toast.makeText(MainActivity.this,"登录失败,服务器或网络出错", Toast.LENGTH_SHORT).show();break;default:break;}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mSp = this.getSharedPreferences("config", this.MODE_PRIVATE);mEtNumber = findViewById(R.id.et_number);mEtPassword = findViewById(R.id.et_password);mCbRemember = findViewById(R.id.cb_remember);mBtLogin = findViewById(R.id.bt_login);mBtLogin.setOnClickListener(this);restoreInfo();}/*** 从sp文件当中读取信息*/private void restoreInfo() {String number = mSp.getString("number", "");String password = mSp.getString("password", "");mEtNumber.setText(number);mEtPassword.setText(password);}/*** 登录按钮的点击事件* @param v*/@Overridepublic void onClick(View v) {final String number =  mEtNumber.getText().toString().trim();final String password =  mEtPassword.getText().toString().trim();if (TextUtils.isEmpty(number) || TextUtils.isEmpty(password)) {Toast.makeText(this,"用户名和密码不能为空", Toast.LENGTH_SHORT).show();return;} else {// 判断是否需要记录用户名和密码if (mCbRemember.isChecked()) {// 被选中状态,需要记录用户名和密码// 需要将数据保存到sp文件当中SharedPreferences.Editor editor = mSp.edit();editor.putString("number", number);editor.putString("password", password);editor.commit();// 提交数据,类似关闭流,事务}new Thread(){@Overridepublic void run() {try {String urlPath = "http://192.168.1.130:8080/Day10/LoginServlet?username=" + number + "&password=" + password;URL url = new URL(urlPath);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setConnectTimeout(5000);int code = conn.getResponseCode();if (code == 200) {InputStream is = conn.getInputStream();String result = StreamUtils.readStream(is);Message msg = Message.obtain();msg.what = STATUS_SUCCESS;msg.obj = result;mHandler.sendMessage(msg);} else {Message msg = Message.obtain();msg.what = STATUS_ERROR;mHandler.sendMessage(msg);}} catch (Exception e) {e.printStackTrace();Message msg = Message.obtain();msg.what = STATUS_ERROR;mHandler.sendMessage(msg);}}}.start();}}}

5.StreamUtils.java

package com.glsite.qqloginweb;import android.graphics.Bitmap;
import android.graphics.BitmapFactory;import java.io.ByteArrayOutputStream;
import java.io.InputStream;/*** @author glsite.com* @version $Rev$* @des ${TODO}* @updateAuthor $Author$* @updateDes ${TODO}*/
public class StreamUtils {public static String readStream(InputStream is){try {ByteArrayOutputStream baos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while(( len = is.read(buffer))!=-1){baos.write(buffer, 0, len);}is.close();String result = baos.toString();if(result.contains("gb2312")){return baos.toString("gb2312");}else{return result;}} catch (Exception e) {e.printStackTrace();return null;}}public static Bitmap readBitmap(InputStream is){return BitmapFactory.decodeStream(is);}
}

测试:

package com.glsite.qqloginweb;import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;import org.junit.Test;
import org.junit.runner.RunWith;import static org.junit.Assert.*;/*** Instrumented test, which will execute on an Android device.** @see <a href="http://d.android.com/tools/testing">Testing documentation</a>*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {@Testpublic void useAppContext() {// Context of the app under test.Context appContext = InstrumentationRegistry.getTargetContext();assertEquals("com.glsite.qqloginweb", appContext.getPackageName());}
}
package com.glsite.qqloginweb;import org.junit.Test;import static org.junit.Assert.*;/*** Example local unit test, which will execute on the development machine (host).** @see <a href="http://d.android.com/tools/testing">Testing documentation</a>*/
public class ExampleUnitTest {@Testpublic void addition_isCorrect() {assertEquals(4, 2 + 2);}
}

================================================================================

2.post请求实现登入

用runOnUiThread,不用 Handler

MainActivity.java

package com.glsite.qqloginweb;import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;public class MainActivity extends AppCompatActivity implements View.OnClickListener {private static final int STATUS_SUCCESS = 1;private static final int STATUS_ERROR = 2;private EditText mEtNumber;private EditText mEtPassword;private CheckBox mCbRemember;private Button mBtLogin;private SharedPreferences mSp;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mSp = this.getSharedPreferences("config", this.MODE_PRIVATE);mEtNumber = findViewById(R.id.et_number);mEtPassword = findViewById(R.id.et_password);mCbRemember = findViewById(R.id.cb_remember);mBtLogin = findViewById(R.id.bt_login);mBtLogin.setOnClickListener(this);restoreInfo();}/*** 从sp文件当中读取信息*/private void restoreInfo() {String number = mSp.getString("number", "");String password = mSp.getString("password", "");mEtNumber.setText(number);mEtPassword.setText(password);}/*** 登录按钮的点击事件* @param v*/@Overridepublic void onClick(View v) {final String number =  mEtNumber.getText().toString().trim();final String password =  mEtPassword.getText().toString().trim();if (TextUtils.isEmpty(number) || TextUtils.isEmpty(password)) {Toast.makeText(this,"用户名和密码不能为空", Toast.LENGTH_SHORT).show();return;} else {// 判断是否需要记录用户名和密码if (mCbRemember.isChecked()) {// 被选中状态,需要记录用户名和密码// 需要将数据保存到sp文件当中SharedPreferences.Editor editor = mSp.edit();editor.putString("number", number);editor.putString("password", password);editor.commit();// 提交数据,类似关闭流,事务}new Thread(){@Overridepublic void run() {try {String urlPath = "http://192.168.1.130:8080/Day10/LoginServlet";URL url = new URL(urlPath);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("POST");conn.setConnectTimeout(5000);conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 设置发送的数据为表单类型,会被添加到http body当中String data = "username=" + URLEncoder.encode(number, "utf-8") + "&password=" + URLEncoder.encode(password, "utf-8");conn.setRequestProperty("Content-Length", String.valueOf(data.length()));// post的请求是把数据以流的方式写了服务器// 指定请求输出模式conn.setDoOutput(true);conn.getOutputStream().write(data.getBytes());int code = conn.getResponseCode();if (code == 200) {InputStream is = conn.getInputStream();String result = StreamUtils.readStream(is);showToastInAnyThread(result);} else {showToastInAnyThread("请求失败");}} catch (Exception e) {e.printStackTrace();showToastInAnyThread("请求失败");}}}.start();}}/*** 在任意现成当中都可以调用弹出吐司的方法* @param result*/private void showToastInAnyThread(final String result) {runOnUiThread(new Runnable() {@Overridepublic void run() {Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();}});}}

StreamUtils.java

package com.glsite.qqloginweb;import android.graphics.Bitmap;
import android.graphics.BitmapFactory;import java.io.ByteArrayOutputStream;
import java.io.InputStream;/*** @author glsite.com* @version $Rev$* @des ${TODO}* @updateAuthor $Author$* @updateDes ${TODO}*/
public class StreamUtils {public static String readStream(InputStream is){try {ByteArrayOutputStream baos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while(( len = is.read(buffer))!=-1){baos.write(buffer, 0, len);}is.close();String result = baos.toString();if(result.contains("gb2312")){return baos.toString("gb2312");}else{return result;}} catch (Exception e) {e.printStackTrace();return null;}}public static Bitmap readBitmap(InputStream is){return BitmapFactory.decodeStream(is);}
}

android仿qq登陆demo,runOnUiThread,Handler相关推荐

  1. Android仿QQ登陆

      今天根据腾讯qq,我们做一个练习,来学习如何制作一个漂亮的布局.首先看一下官方图片 还是一个启动画面,之后进入登录页面,导航页面就不介绍了,大家可以参考微信的导航页面.首先程序进入SplashAc ...

  2. android里qq登录界面,Android仿QQ登陆窗口实现原理

    今天根据腾讯qq,我们做一个练习,来学习如何制作一个漂亮的布局.首先看一下官方图片 还是一个启动画面,之后进入登录页面,导航页面就不介绍了,大家可以参考微信的导航页面.首先程序进入SplashActi ...

  3. android 仿QQ登陆界面实现

    android 现在越来越火,之前大量的桌面软件,现在都开发出android版了.最近也在学习android,顺便做了几个demo.不说废话了,上图. 接下来是布局: <RelativeLayo ...

  4. php仿qq登录界面安卓,Android_Android仿QQ登陆窗口实现原理,今天根据腾讯qq,我们做一个 - phpStudy...

    Android仿QQ登陆窗口实现原理 今天根据腾讯qq,我们做一个练习,来学习如何制作一个漂亮的布局.首先看一下官方图片 还是一个启动画面,之后进入登录页面,导航页面就不介绍了,大家可以参考微信的导航 ...

  5. Android仿QQ实现聊天功能

    前段时间下载了Android仿QQ界面和聊天的Demo,发现很有意思,于是研究了一下并自己在此基础上集成环信实现了在线聊天功能,可以实现注册.加人.审核通知.推送.创建群组.群组聊天,并加入了炫酷的背 ...

  6. Android仿QQ空间底部菜单

    之前曾经在网上看到Android仿QQ空间底部菜单的Demo,发现这个Demo有很多Bug,布局用了很多神秘数字.于是研究了一下QQ空间底部菜单的实现,自己写了一个,供大家参考.效果如下图所示:  点 ...

  7. Android仿QQ侧滑菜单

    先上效果图: GIF图有点模糊,源码已上传Github:Android仿QQ侧滑菜单 ####整体思路: 自定义ItemView的根布局(SwipeMenuLayout extends LinearL ...

  8. android qq分组展开,Android仿qq分组管理的第三方库

    本文实例为大家分享了Android仿qq分组管理的第三方库,供大家参考,具体内容如下 下面先看效果 我们点击展开与折叠分组的功能在库里面是已经封装好的,只能把它已入到项目中,就可以直接用了,十分的方便 ...

  9. 新手利用C# 实现简单仿QQ登陆注册功能

    闲来没事,想做一个仿QQ登陆注册的winform,于是利用工作之余,根据自己的掌握和查阅的资料,历时4天修改完成,新手水平,希望和大家共同学习进步,有不同见解希望提出! 废话不多说,进入正题: 先来看 ...

最新文章

  1. 这谁顶得住?mybatis十八连环问!
  2. php删除数组中指定值的元素
  3. 洛谷P4216 [SCOI2015]情报传递(树剖+主席树)
  4. 哀悼与感动同在[转载]
  5. windows下打开jenkins
  6. JEECG传统版问题分析
  7. IE haslayout总结
  8. 三菱GXWorks2 多CPU参数设置
  9. 用CSS3制作50个超棒动画效果教程
  10. 王超(清华大学博士)Linux期末考核
  11. gridview隐藏列的方法
  12. Git报错remote: error: hook declined to update refs/heads/feature/XXX
  13. mysql union 慢_mysql查询慢的原因和解决方案
  14. IE浏览器如何实现断点续传
  15. 运行java提示找不到符号_运行java代码时出现找不到符号错误怎么解决
  16. 一种简单、安全的Dota全图新思路 作者:LC 【转】
  17. golang封装mysql涉及到的包以及sqlx和gorm的区别
  18. eas-dep添加白名单
  19. 2020-11-23
  20. 闭关修炼30天,“啃透”这658页PDF,成功定级阿里P7

热门文章

  1. 引路蜂地图API:Gis.Raster 包定义
  2. Response.Cookie FF
  3. layui 如何清空form表单
  4. c# 类属性和方法
  5. odoo里用sql语句说为日期date类型,没有转换为字符串。
  6. 实体框架 Code First 迁移命令
  7. C语言中的undefined behavior系列(2)-- lifetime of object
  8. Windows电脑无法上网排错思路
  9. PowerLinux 服务器上安装 Oracle (详细步骤)
  10. Linux下开源邮件系统Postfix+Extmail+Extman环境部署