SettingsActivity.java 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. package com.ht.gate;
  2. import android.annotation.SuppressLint;
  3. import android.app.AlertDialog;
  4. import android.app.PendingIntent;
  5. import android.app.ProgressDialog;
  6. import android.content.ComponentName;
  7. import android.content.Context;
  8. import android.content.DialogInterface;
  9. import android.content.Intent;
  10. import android.content.IntentSender;
  11. import android.content.ServiceConnection;
  12. import android.content.SharedPreferences;
  13. import android.content.pm.PackageInstaller;
  14. import android.net.Uri;
  15. import android.os.Bundle;
  16. import android.os.IBinder;
  17. import android.provider.Settings;
  18. import android.text.TextUtils;
  19. import android.util.Log;
  20. import android.view.View;
  21. import android.widget.TextView;
  22. import androidx.annotation.NonNull;
  23. import androidx.annotation.Nullable;
  24. import androidx.appcompat.app.AppCompatActivity;
  25. import com.blankj.utilcode.constant.PermissionConstants;
  26. import com.blankj.utilcode.util.AppUtils;
  27. import com.blankj.utilcode.util.PathUtils;
  28. import com.blankj.utilcode.util.PermissionUtils;
  29. import com.blankj.utilcode.util.ToastUtils;
  30. import com.ht.gate.domain.QueryUpdate;
  31. import com.ht.gate.domain.Room;
  32. import com.ht.gate.domain.UpdateInfo;
  33. import com.liulishuo.okdownload.DownloadListener;
  34. import com.liulishuo.okdownload.DownloadTask;
  35. import com.liulishuo.okdownload.SpeedCalculator;
  36. import com.liulishuo.okdownload.StatusUtil;
  37. import com.liulishuo.okdownload.core.Util;
  38. import com.liulishuo.okdownload.core.breakpoint.BlockInfo;
  39. import com.liulishuo.okdownload.core.breakpoint.BreakpointInfo;
  40. import com.liulishuo.okdownload.core.cause.EndCause;
  41. import com.liulishuo.okdownload.core.cause.ResumeFailedCause;
  42. import com.liulishuo.okdownload.core.listener.DownloadListener4WithSpeed;
  43. import com.liulishuo.okdownload.core.listener.assist.Listener4SpeedAssistExtend;
  44. import java.io.File;
  45. import java.io.IOException;
  46. import java.io.InputStream;
  47. import java.io.OutputStream;
  48. import java.util.List;
  49. import java.util.Map;
  50. import butterknife.BindView;
  51. import butterknife.ButterKnife;
  52. import butterknife.OnClick;
  53. import es.dmoral.toasty.Toasty;
  54. import retrofit2.Call;
  55. import retrofit2.Callback;
  56. import retrofit2.Response;
  57. @SuppressLint("SetTextI18n")
  58. public class SettingsActivity extends AppCompatActivity {
  59. private static final String TAG = "SettingsActivity";
  60. @BindView(R.id.tv_title)
  61. TextView tvTitle;
  62. @BindView(R.id.tv_space_id)
  63. TextView tvSpaceId;
  64. @BindView(R.id.tv_address)
  65. TextView tvAddress;
  66. @BindView(R.id.tv_site_name)
  67. TextView tvSiteName;
  68. @BindView(R.id.tv_version)
  69. TextView tvVersion;
  70. public static final String PREF_NAME_SETTINGS = "settings";
  71. public static final String PREF_KEY_ADDRESS = "address";
  72. private SharedPreferences sharedPreferences;
  73. private DoorService.DoorBinder mDoorBinder;
  74. private ProgressDialog progressDialog;
  75. private ProgressDialog loadingDialog;
  76. private ServiceConnection connection = new ServiceConnection() {
  77. @Override
  78. public void onServiceConnected(ComponentName name, IBinder service) {
  79. Log.d(TAG, "onServiceConnected");
  80. mDoorBinder = (DoorService.DoorBinder) service;
  81. }
  82. @Override
  83. public void onServiceDisconnected(ComponentName name) {
  84. Log.d(TAG, "onServiceDisconnected");
  85. mDoorBinder = null;
  86. }
  87. };
  88. @Override
  89. protected void onCreate(Bundle savedInstanceState) {
  90. super.onCreate(savedInstanceState);
  91. setContentView(R.layout.activity_settings);
  92. ButterKnife.bind(this);
  93. sharedPreferences = getSharedPreferences(PREF_NAME_SETTINGS, MODE_PRIVATE);
  94. bindService(new Intent(this, DoorService.class), connection, BIND_AUTO_CREATE);
  95. progressDialog = new ProgressDialog(this, AlertDialog.THEME_DEVICE_DEFAULT_DARK);
  96. progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  97. progressDialog.setCanceledOnTouchOutside(false);
  98. progressDialog.setCancelable(false);
  99. progressDialog.setMessage("下载中");
  100. progressDialog.setProgress(0);
  101. loadingDialog = new ProgressDialog(this, AlertDialog.THEME_DEVICE_DEFAULT_DARK);
  102. loadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
  103. loadingDialog.setCanceledOnTouchOutside(false);
  104. loadingDialog.setCancelable(false);
  105. loadingDialog.setMessage("加载中");
  106. }
  107. @Override
  108. protected void onResume() {
  109. super.onResume();
  110. View decorView = getWindow().getDecorView();
  111. int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
  112. | View.SYSTEM_UI_FLAG_FULLSCREEN
  113. | View.SYSTEM_UI_FLAG_IMMERSIVE;
  114. decorView.setSystemUiVisibility(uiOptions);
  115. Room room = Room.fromBase64(sharedPreferences.getString(Constants.PREF_ROOM_INFO, null));
  116. if (room != null) {
  117. tvTitle.setText(room.getRoomName() + room.getRoomBizNum());
  118. tvSpaceId.setText(room.getDeviceCode());
  119. if (!TextUtils.isEmpty(room.getSiteName())) {
  120. tvSiteName.setText(room.getSiteName());
  121. tvSiteName.setVisibility(View.VISIBLE);
  122. } else {
  123. tvSiteName.setVisibility(View.GONE);
  124. }
  125. }
  126. tvAddress.setText(sharedPreferences.getString(PREF_KEY_ADDRESS, ""));
  127. tvVersion.setText(AppUtils.getAppVersionName() + " (" + AppUtils.getAppVersionCode() + ")");
  128. }
  129. @Override
  130. protected void onDestroy() {
  131. super.onDestroy();
  132. if (connection != null) {
  133. unbindService(connection);
  134. }
  135. }
  136. @OnClick(R.id.btn_back)
  137. void back() {
  138. finish();
  139. }
  140. @OnClick(R.id.btn_change_space_id)
  141. void changeSpaceId() {
  142. Intent intent = new Intent(this, LoginActivity.class);
  143. intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
  144. | Intent.FLAG_ACTIVITY_CLEAR_TASK);
  145. startActivity(intent);
  146. finish();
  147. }
  148. @OnClick(R.id.btn_change_address)
  149. void changeAddress() {
  150. new PromptBuilder(this)
  151. .setTitle("输入空间门禁地址")
  152. .setValue(tvAddress.getText().toString())
  153. .setPositiveButton("确定")
  154. .setNegativeButton("取消")
  155. .setPromptListener(new PromptBuilder.PromptListener() {
  156. @Override
  157. public void onCancel(DialogInterface dialog) {
  158. dialog.dismiss();
  159. }
  160. @Override
  161. public void onConfirm(DialogInterface dialog, String value) {
  162. dialog.dismiss();
  163. tvAddress.setText(value);
  164. sharedPreferences.edit()
  165. .putString(PREF_KEY_ADDRESS, value)
  166. .apply();
  167. if (mDoorBinder != null) {
  168. mDoorBinder.getService().restartSocket();
  169. }
  170. }
  171. })
  172. .show();
  173. }
  174. @OnClick(R.id.btn_update)
  175. void checkUpdate() {
  176. try {
  177. Room room = Room.fromBase64(sharedPreferences.getString(Constants.PREF_ROOM_INFO, null));
  178. RetrofitManager.getInstance().getRetrofit().create(ApiService.class)
  179. .checkUpdate(new QueryUpdate(room.getSiteCode(), "02", AppUtils.getAppVersionCode() + ""))
  180. .enqueue(new Callback<UpdateInfo>() {
  181. @Override
  182. public void onResponse(Call<UpdateInfo> call, Response<UpdateInfo> response) {
  183. loadingDialog.dismiss();
  184. if (response.code() == 200) {
  185. if (response.body() == null) {
  186. Toasty.info(SettingsActivity.this, "暂无更新").show();
  187. return;
  188. }
  189. if (response.body().getResultData().isNeedUpdate()) {
  190. new AlertDialog.Builder(SettingsActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_DARK)
  191. .setTitle("新版本")
  192. .setMessage("检测到新版本" + response.body().getResultData().getNewestVersion() + ",是否立即下载更新?")
  193. .setNegativeButton("取消", (dialog0, which0) -> {
  194. dialog0.dismiss();
  195. })
  196. .setPositiveButton("下载", (dialog0, which0) -> {
  197. dialog0.dismiss();
  198. PermissionUtils.permission(PermissionConstants.STORAGE)
  199. .rationale((activity, shouldRequest) -> new AlertDialog.Builder(activity, AlertDialog.THEME_DEVICE_DEFAULT_DARK)
  200. .setTitle("无写入权限")
  201. .setMessage("请前往设置打开存储权限")
  202. .setNegativeButton("取消", (dialog, which) -> {
  203. dialog.dismiss();
  204. activity.finish();
  205. })
  206. .setPositiveButton("打开设置", (dialog, which) -> {
  207. dialog.dismiss();
  208. Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
  209. Uri uri = Uri.fromParts("package", getPackageName(), null);
  210. intent.setData(uri);
  211. intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
  212. intent.addCategory(Intent.CATEGORY_DEFAULT);
  213. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  214. intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
  215. intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  216. activity.startActivity(intent);
  217. activity.finish();
  218. }).show())
  219. .callback(new PermissionUtils.SimpleCallback() {
  220. @Override
  221. public void onGranted() {
  222. String url;
  223. if (response.body().getResultData().getSoftwareUrl().startsWith("http")) {
  224. url = response.body().getResultData().getSoftwareUrl();
  225. } else {
  226. url = RetrofitManager.BASE_URL.replaceAll("/$", "") + response.body().getResultData().getSoftwareUrl();
  227. }
  228. Log.d(TAG, "download Url: " + url);
  229. startDownload2(url);
  230. }
  231. @Override
  232. public void onDenied() {
  233. }
  234. }).request();
  235. }).show();
  236. } else {
  237. Toasty.info(SettingsActivity.this, "暂无更新").show();
  238. }
  239. }
  240. }
  241. @Override
  242. public void onFailure(Call<UpdateInfo> call, Throwable t) {
  243. loadingDialog.dismiss();
  244. Toasty.info(SettingsActivity.this, "暂无更新").show();
  245. }
  246. });
  247. } catch (Exception e) {
  248. e.printStackTrace();
  249. Toasty.info(SettingsActivity.this, e.getMessage()).show();
  250. }
  251. // PermissionUtils.permission(PermissionConstants.STORAGE)
  252. // .rationale((activity, shouldRequest) -> new AlertDialog.Builder(activity, AlertDialog.THEME_DEVICE_DEFAULT_DARK)
  253. // .setTitle("无写入权限")
  254. // .setMessage("请前往设置打开存储权限")
  255. // .setNegativeButton("取消", (dialog, which) -> {
  256. // dialog.dismiss();
  257. // activity.finish();
  258. // })
  259. // .setPositiveButton("打开设置", (dialog, which) -> {
  260. // dialog.dismiss();
  261. // Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
  262. // Uri uri = Uri.fromParts("package", getPackageName(), null);
  263. // intent.setData(uri);
  264. // intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
  265. // intent.addCategory(Intent.CATEGORY_DEFAULT);
  266. // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  267. // intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
  268. // intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  269. // activity.startActivity(intent);
  270. // activity.finish();
  271. // }).show())
  272. // .callback(new PermissionUtils.SimpleCallback() {
  273. // @Override
  274. // public void onGranted() {
  275. // startDownload("https://beautiful-nanjing.oss-cn-hangzhou.aliyuncs.com/Coolapk-v10.2-2005181-coolapk-app-release.apk");
  276. // }
  277. //
  278. // @Override
  279. // public void onDenied() {
  280. //
  281. // }
  282. // }).request();
  283. }
  284. // private void startDownload(String url) {
  285. // FileDownloader.setup(SettingsActivity.this);
  286. // String ext = FilenameUtils.getExtension(url);
  287. // String fileName = System.currentTimeMillis() + ".apk";
  288. // String path = PathUtils.getExternalAppDownloadPath() + "/" + fileName;
  289. // BaseDownloadTask downloadTask = FileDownloader.getImpl().create(url).setPath(path).setListener(new FileDownloadListener() {
  290. // @Override
  291. // protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
  292. //
  293. // }
  294. //
  295. // @Override
  296. // protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
  297. // Log.d(TAG, "download progress: " + soFarBytes + " / " + totalBytes);
  298. // progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  299. // progressDialog.setProgress((int) (soFarBytes * 100L / totalBytes));
  300. // }
  301. //
  302. // @Override
  303. // protected void completed(BaseDownloadTask task) {
  304. // progressDialog.dismiss();
  305. // ToastUtils.showShort("下载完成");
  306. // installApk(new File(task.getPath()));
  307. // }
  308. //
  309. // @Override
  310. // protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
  311. // }
  312. //
  313. // @Override
  314. // protected void error(BaseDownloadTask task, Throwable e) {
  315. // progressDialog.dismiss();
  316. // ToastUtils.showShort(e.getMessage());
  317. // }
  318. //
  319. // @Override
  320. // protected void warn(BaseDownloadTask task) {
  321. //
  322. // }
  323. // });
  324. // progressDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, "取消下载", (dialog, which) -> {
  325. // downloadTask.pause();
  326. // progressDialog.dismiss();
  327. // });
  328. // progressDialog.setProgress(0);
  329. // progressDialog.show();
  330. // downloadTask.start();
  331. // }
  332. private void startDownload2(String url) {
  333. String fileName = System.currentTimeMillis() + ".apk";
  334. DownloadTask task = new DownloadTask.Builder(url, PathUtils.getExternalAppDownloadPath(), fileName)
  335. .setMinIntervalMillisCallbackProcess(16)
  336. .setConnectionCount(1)
  337. // ignore the same task has already completed in the past.
  338. .setPassIfAlreadyCompleted(false)
  339. .build();
  340. Util.enableConsoleLog();
  341. // task.enqueue(new DownloadListener() {
  342. // @Override
  343. // public void taskStart(@NonNull DownloadTask task) {
  344. // Log.d(TAG, "taskStart");
  345. // }
  346. //
  347. // @Override
  348. // public void connectTrialStart(@NonNull DownloadTask task, @NonNull Map<String, List<String>> requestHeaderFields) {
  349. // Log.d(TAG, "connectTrialStart");
  350. // }
  351. //
  352. // @Override
  353. // public void connectTrialEnd(@NonNull DownloadTask task, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields) {
  354. // Log.d(TAG, "connectTrialEnd");
  355. // }
  356. //
  357. // @Override
  358. // public void downloadFromBeginning(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull ResumeFailedCause cause) {
  359. // Log.d(TAG, "downloadFromBeginning");
  360. // }
  361. //
  362. // @Override
  363. // public void downloadFromBreakpoint(@NonNull DownloadTask task, @NonNull BreakpointInfo info) {
  364. // Log.d(TAG, "downloadFromBreakpoint");
  365. // }
  366. //
  367. // @Override
  368. // public void connectStart(@NonNull DownloadTask task, int blockIndex, @NonNull Map<String, List<String>> requestHeaderFields) {
  369. // Log.d(TAG, "connectStart");
  370. // }
  371. //
  372. // @Override
  373. // public void connectEnd(@NonNull DownloadTask task, int blockIndex, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields) {
  374. // Log.d(TAG, "connectEnd");
  375. // }
  376. //
  377. // @Override
  378. // public void fetchStart(@NonNull DownloadTask task, int blockIndex, long contentLength) {
  379. //
  380. // Log.d(TAG, String.format("fetchStart blockIndex %s contentLength %s", blockIndex, contentLength));
  381. // }
  382. //
  383. // @Override
  384. // public void fetchProgress(@NonNull DownloadTask task, int blockIndex, long increaseBytes) {
  385. // Log.d(TAG, String.format("fetchProgress blockIndex %s increaseBytes %s", blockIndex, increaseBytes));
  386. // }
  387. //
  388. // @Override
  389. // public void fetchEnd(@NonNull DownloadTask task, int blockIndex, long contentLength) {
  390. // Log.d(TAG, "fetchEnd");
  391. // }
  392. //
  393. // @Override
  394. // public void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause) {
  395. // Log.d(TAG, "taskEnd");
  396. // }
  397. // });
  398. progressDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, "取消下载", (dialog, which) -> {
  399. task.cancel();
  400. progressDialog.dismiss();
  401. });
  402. progressDialog.setProgress(0);
  403. progressDialog.show();
  404. final long[] totalLength = {0};
  405. task.enqueue(new DownloadListener4WithSpeed() {
  406. @Override
  407. public void taskStart(@NonNull DownloadTask task) {
  408. Log.d(TAG, "taskStart");
  409. }
  410. @Override
  411. public void connectStart(@NonNull DownloadTask task, int blockIndex, @NonNull Map<String, List<String>> requestHeaderFields) {
  412. Log.d(TAG, "connectStart");
  413. }
  414. @Override
  415. public void connectEnd(@NonNull DownloadTask task, int blockIndex, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields) {
  416. Log.d(TAG, "connectEnd");
  417. }
  418. @Override
  419. public void infoReady(@NonNull DownloadTask task, @NonNull BreakpointInfo info, boolean fromBreakpoint, @NonNull Listener4SpeedAssistExtend.Listener4SpeedModel model) {
  420. totalLength[0] = info.getTotalLength();
  421. Log.d(TAG, "infoReady");
  422. }
  423. @Override
  424. public void progressBlock(@NonNull DownloadTask task, int blockIndex, long currentBlockOffset, @NonNull SpeedCalculator blockSpeed) {
  425. Log.d(TAG, "progressBlock");
  426. }
  427. @Override
  428. public void progress(@NonNull DownloadTask task, long currentOffset, @NonNull SpeedCalculator taskSpeed) {
  429. Log.d(TAG, String.format("progress currentOffset %s ", currentOffset));
  430. progressDialog.setProgress((int) (currentOffset * 100 / totalLength[0]));
  431. }
  432. @Override
  433. public void blockEnd(@NonNull DownloadTask task, int blockIndex, BlockInfo info, @NonNull SpeedCalculator blockSpeed) {
  434. Log.d(TAG, "blockEnd");
  435. }
  436. @Override
  437. public void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause, @NonNull SpeedCalculator taskSpeed) {
  438. Log.d(TAG, "taskEnd");
  439. progressDialog.dismiss();
  440. if (cause == EndCause.COMPLETED) {
  441. installApk(task.getFile());
  442. } else {
  443. Toasty.info(SettingsActivity.this, cause.name()).show();
  444. }
  445. }
  446. });
  447. }
  448. private void installApk(File apkFile) {
  449. // Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
  450. // intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
  451. // intent.setDataAndType(FileProvider.getUriForFile(SettingsActivity.this,
  452. // "com.ht.gate.fileProvider", apkFile), "application/vnd.android.package-archive");
  453. // startActivity(intent);
  454. AppUtils.installApp(apkFile);
  455. // try {
  456. // installPackage(apkFile.getPath());
  457. // } catch (IOException e) {
  458. // e.printStackTrace();
  459. // }
  460. }
  461. public void installPackage(String filename) throws IOException {
  462. PackageInstaller packageInstaller = getApplicationContext().getPackageManager().getPackageInstaller();
  463. Log.i(TAG, "JIntentActionInstallApk - got packageInstaller");
  464. PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
  465. PackageInstaller.SessionParams.MODE_FULL_INSTALL);
  466. Log.i(TAG, "JIntentActionInstallApk - set SessionParams");
  467. int sessionId = packageInstaller.createSession(params);
  468. PackageInstaller.Session session = packageInstaller.openSession(sessionId);
  469. Log.i(TAG, "JIntentActionInstallApk - session opened");
  470. // Create an install status receiver.
  471. Context context = getApplicationContext();
  472. addApkToInstallSession(context, filename, session);
  473. Log.i(TAG, "JIntentActionInstallApk - apk added to session");
  474. Intent intent = new Intent(context, MainActivity.class);
  475. intent.setAction("PACKAGE_INSTALLED_ACTION");
  476. PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
  477. IntentSender statusReceiver = pendingIntent.getIntentSender();
  478. // Commit the session (this will start the installation workflow).
  479. session.commit(statusReceiver);
  480. Log.i(TAG, "JIntentActionInstallApk - commited");
  481. }
  482. private static void addApkToInstallSession(Context context, String filename, PackageInstaller.Session session) {
  483. Log.i(TAG, "addApkToInstallSession " + filename);
  484. // It's recommended to pass the file size to openWrite(). Otherwise installation may fail
  485. // if the disk is almost full.
  486. try {
  487. OutputStream packageInSession = session.openWrite("package", 0, -1);
  488. InputStream input;
  489. Uri uri = Uri.parse(filename);
  490. input = context.getContentResolver().openInputStream(uri);
  491. if (input != null) {
  492. Log.i(TAG, "input.available: " + input.available());
  493. byte[] buffer = new byte[16384];
  494. int n;
  495. while ((n = input.read(buffer)) >= 0) {
  496. packageInSession.write(buffer, 0, n);
  497. }
  498. } else {
  499. Log.i(TAG, "addApkToInstallSession failed");
  500. throw new IOException("addApkToInstallSession");
  501. }
  502. packageInSession.close(); //need to close this stream
  503. input.close(); //need to close this stream
  504. } catch (Exception e) {
  505. Log.i(TAG, "addApkToInstallSession failed2 " + e.toString());
  506. }
  507. }
  508. }