編輯:關於 Android 程式設計
用手機掃一下螢幕上的二維碼就完成網頁登入,這個體驗現在很常見。它的原理其實不複雜,核心就是「以二維碼裡的 uuid 作為一座橋」,把手機端已登入的狀態傳回網頁端。
1. 網頁端產生二維碼,同時生成一個 uuid 並寫入資料庫;
2. 網頁端持續輪詢,檢查資料庫中該 uuid 是否已有掃描/登入資訊;
3. 手機掃描二維碼取得 uuid,連同使用者帳號密碼一起回傳給伺服器;
4. 伺服器驗證帳密後,把登入資訊寫回該 uuid 對應的紀錄;
5. 網頁端的輪詢查到完整登入資訊,登入成功。
以下示範採用 Java EE(Servlet + Hibernate)搭配 Android 原生掃碼模組的組合。
二維碼的產生交給開源的 QRCode.jar 處理,下載後放入 WEB-INF/lib 即可。
@Entity
@Table(name = "UserLogin")
public class UserLogin {
@Id
@GeneratedValue(generator = "UserLoginIdGenerator")
@GenericGenerator(name = "UserLoginIdGenerator", strategy = "uuid")
private String id;
@Column
private String name;
@Column
private String password;
@Column
private int uuid;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getUuid() {
return uuid;
}
public void setUuid(int uuid) {
this.uuid = uuid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
二維碼的內容刻意設計成一段 JSON,同時帶上後端位址與 uuid,這樣手機端解析起來比較省事。
public class GetQrCodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
// 產生唯一識別碼
int uuid = (int) (Math.random() * 100000);
// 二維碼內容:後端接收位址 + uuid
JSONObject obj = new JSONObject();
obj.put("url", "https://192.168.0.199:8080/QrCodeLogin/PhoneLoginServlet");
obj.put("uuid", uuid);
String content = obj.toString();
System.out.println("obj:" + content);
String imgName = uuid + "_" + (int) (new Date().getTime() / 1000) + ".png";
String webpath = request.getSession().getServletContext().getRealPath("/");
String imgPath = webpath + "/img/qrCodeImg/" + imgName;
String logoPath = webpath + "/img/logo.png";
QRCodeUtil handler = new QRCodeUtil();
// 在二維碼中央加上 logo
handler.encoderQRCode(content, imgPath, logoPath, "png");
// 把 uuid 存進資料庫,等待手機端回傳登入資訊
SessionFactory sf = HibernateUtil.getSessionFacotry();
Session session = sf.openSession();
session.beginTransaction();
UserLogin userlogin = new UserLogin();
userlogin.setUuid(uuid);
session.save(userlogin);
session.getTransaction().commit();
session.close();
sf = null;
String qrCodeImg = "https://192.168.0.199:8080/QrCodeLogin/img/qrCodeImg/" + imgName;
String jsonStr = "{\"uuid\":" + uuid + ",\"qrCodeImg\":\"" + qrCodeImg + "\"}";
out.print(jsonStr);
out.flush();
out.close();
}
}
這裡用「長連接 + 輪詢」的折衷做法:請求進來後在伺服器端迴圈等待,查到結果或逾時才回應,避免前端建立過於頻繁的請求。
public class LongConnectionCheckServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int uuid = Integer.parseInt(request.getParameter("uuid"));
String jsonStr = "";
long inTime = new Date().getTime();
Boolean bool = true;
while (bool) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 以 uuid 查詢登入表
String username = "";
SessionFactory sf = HibernateUtil.getSessionFacotry();
Session session = sf.openSession();
Criteria criteria = session.createCriteria(UserLogin.class);
criteria.add(Restrictions.eq("uuid", uuid));
List result = criteria.list();
if (result.size() > 0) {
for (UserLogin s : result) {
username = s.getName();
if (!"".equals(username) && username != null) {
// 使用者名稱不為空,代表登入成功
bool = false;
session.clear();
session.beginTransaction();
session.delete(s); // 刪除紀錄,二維碼即刻失效
session.getTransaction().commit();
}
jsonStr = "{\"uname\":\"" + username + "\"}";
System.out.println(username);
}
} else {
// 查不到紀錄,代表二維碼已使用或過期
if (new Date().getTime() - inTime > 5000) {
bool = false;
}
}
session.close();
sf = null;
}
System.out.println("login ok : " + jsonStr);
PrintWriter out = response.getWriter();
out.print(jsonStr);
out.flush();
out.close();
}
}
public class PhoneLoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int uuid = Integer.parseInt(request.getParameter("uuid"));
String uname = request.getParameter("uname");
String upwd = request.getParameter("upwd");
boolean bool = true; // 是否仍需處理
boolean islogin = false; // 登入結果
if (bool) {
SessionFactory sf = HibernateUtil.getSessionFacotry();
Session session = sf.openSession();
Criteria criteria = session.createCriteria(UserLogin.class);
criteria.add(Restrictions.eq("uuid", uuid));
List result = criteria.list();
if (result.size() > 0) {
for (UserLogin s : result) {
s.setName(uname);
s.setPassword(upwd);
session.clear();
session.beginTransaction();
session.saveOrUpdate(s);
session.getTransaction().commit();
bool = false;
islogin = true;
}
} else {
// 查無此 uuid,代表二維碼已過期
islogin = false;
System.out.println("二維碼已過期,請重新整理頁面");
}
session.close();
sf = null;
}
PrintWriter out = response.getWriter();
out.print(islogin);
out.flush();
out.close();
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>掃碼登入</title>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<style type="text/css">
.div-content { text-align: center; }
.img { margin-top: 150px; }
.div-content-text { text-align: center; margin-top: 20px; font-size: 36px; color: blue; }
</style>
</head>
<body>
<div class="div-content">
<img class="img" src="" alt="二維碼" />
<div class="div-content-text">掃描二維碼登入</div>
</div>
</body>
</html>

掃碼能力來自 zxing 的 Android 移植版本,把 BarCodeLibrary 作為依賴工程引入即可。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="@+id/btn_scan"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@android:color/holo_blue_light"
android:gravity="center"
android:text="掃碼登錄"
android:textColor="@android:color/white" />
</LinearLayout>
點擊按鈕後跳進掃碼頁,拿到結果後解析 JSON,取出 uuid 與回傳位址,再用 POST 把帳密送回去。
public class MainActivity extends Activity implements OnClickListener {
private Button btnScan;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnScan = (Button) findViewById(R.id.btn_scan);
btnScan.setOnClickListener(this);
}
@Override
public void onClick(View v) {
startActivityForResult(new Intent(this, CaptureActivity.class), 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
String result = data.getExtras().getString("result");
JSONObject obj = JSONObject.parseObject(result);
String uuid = obj.getString("uuid");
String httpUrl = obj.getString("url");
HttpUtils http = new HttpUtils();
RequestParams params = new RequestParams();
params.addBodyParameter("uuid", uuid);
params.addBodyParameter("uname", "yangjie");
params.addBodyParameter("upwd", "123456");
http.send(HttpRequest.HttpMethod.POST, httpUrl, params, new RequestCallBack() {
@Override
public void onFailure(HttpException arg0, String arg1) {
Toast.makeText(getApplicationContext(), "登陸失敗,二維碼過期,請重新整理頁面!", 1000).show();
}
@Override
public void onSuccess(ResponseInfo arg0) {
Toast.makeText(getApplicationContext(), "登陸成功!", 1000).show();
}
});
}
}
}


這個 Demo 把帳密直接寫在客戶端,僅供理解流程;正式環境應該改成手機端帶著既有的登入 token 去換取網頁端 session,而不是重新輸入一次帳密。
另外,範例中的 uuid 只有六位隨機數,碰撞與被猜到都不難,實作時建議改用更長的隨機字串並加上短效過期機制;輪詢間隔與伺服器端等待時間也需要一起調整,避免佔住過多連線。
ViewPager 多頁面滑動切換與指示條動畫實作
先看成果 要做的是新浪微博那種 Tab 效果:手勢滑動或點擊標題都能切換頁面,而下方那條白色指示條會平滑地滑到對應的頁卡下方。 認識 ViewPager ViewPa
Android 的 TCP 與 UDP 通信:簡易範例與實作要點
TCP 與 UDP 是最常用的兩種網路傳輸方式,協定細節這裡不再贅述。本文重點在於把可直接參考的程式碼整理出來。 先說 TCP:建立連線之後,通信雙方可以同時進行資料傳輸
Android百度地圖之基礎地圖(三):地圖類型、覆蓋物與手勢
借助百度地圖SDK提供的接口,開發者可以直接使用百度提供的基礎地圖數據。目前SDK所提供的地圖等級為3-21級,涵蓋建築物、道路、河流、學校、公園等多種資訊。 自V3.7
仿映客送禮動畫:屬性動畫與佇列策略
效果拆解直播送禮動畫通常包含多個元素:使用者頭像、暱稱、禮物圖示、數量、粒子效果,以及整體飛入、縮放、淡出等動畫。若要把這些效果做出來,可以先把畫面拆成幾個部分,再分別處