近日开发某个APP,需要在dialog点击确定后保存sharedpreferences并发送数据到服务器,安装APK运行onclick后却没有将sharedpreferences写入,于是开启debug模式下断点,看看onclick有没有执行。诡异的是,onclick居然又执行到了,而且sharedpreferences也成功写入。找了半天原因,硬是没找到为何运行不正确。以下是部分(原)代码(嵌在onclick中):
try {
AesCbcWithIntegrity.SecretKeys keys = AesCbcWithIntegrity.generateKey();
final String keystring = keys.toString();
AesCbcWithIntegrity.CipherTextIvMac cipherTextIvMac =
AesCbcWithIntegrity.encrypt(password, keys);
String encryptedPassword = cipherTextIvMac.toString();
String encryptedUID = encrypt(UID,password);
//store encryptedPassword
//and encryptedUID which is encrypted by password
sp = context.getSharedPreferences("User",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("encryptedPassword",encryptedPassword);
editor.putString("encryptedUID",encryptedUID);
editor.putString("UID",UID);
editor.commit();
//send keystring to server
new Thread(new Runnable() {
@Override
public void run() {
HttpsManager httpsManager = HttpsManager.getInstance();
try {
httpsManager.sendKeystring(context,UID,keystring);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}catch (Exception e){
e.printStackTrace();
}
千钧一发之际,突然想到是不是线程的问题,于是看了相关的帖子,找到一篇有关线程池阻塞的帖子(https://blog.youkuaiyun.com/weixin_41101173/article/details/79680643),尝试把sharedpreferences的写入一并放入新线程中写入(我把前面的代码也放进去新线程了,因为前面是一段较为复杂的加密计算),再次运行,居然成功了!
虽说解决问题就好,但是还是有点疑惑,按照那个帖子的说法,线程池阻塞不是应该会应用卡死吗,为什么我这边应用却正常执行下去了,欢迎各位朋友发表见解。。