Method of Android Parsing XML File and Upgrading APK
- 2021-09-24 23:48:40
- OfStack
Installing APK
public class DownLoadApk {
public static SharedPreferences sharedPrederences = null;
// Start the installation interface
public static void DownId(Context context, long downId){
DownloadManager mDownloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = mDownloadManager.getUriForDownloadedFile(downId);
startInstall(context, downloadUri);
}
/**
* Jump to the installation interface
* @param context Scope
* @param uri Package name
*/
private static void startInstall(Context context, Uri uri) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(uri, "application/vnd.android.package-archive");
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(install);
}
// Delete a file
public static boolean fileDelete(String filePath) {
File file = new File(filePath);
if (file.exists() == false) {
return false;
}
return file.delete();
}
Send a request to get the input stream
Thread thread = new Thread() {
@Override
public void run() {
super.run();
//XML Store in ftp The address of the server
String path = FileUtils.getDevice_address()+"News.XML";
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
// Send http GET Request and obtain the corresponding code
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
// Use pull Parser, start parsing this stream
parseNewsXml(is);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
thread.start();
Parsing XML file
private void parseNewsXml(InputStream is) {
XmlPullParser xp = Xml.newPullParser();
try {
xp.setInput(is, "utf-8");
// By judging the event type of the node, we can know what the current node is
int type = xp.getEventType();
News news = null;
while (type != XmlPullParser.END_DOCUMENT) {
switch (type) {
case XmlPullParser.START_TAG:
if ("newslist".equals(xp.getName())) {
newsList = new ArrayList<>();
break;
} else if ("news".equals(xp.getName())) {
news = new News();
break;
} else if ("name".equals(xp.getName())) {
String name = xp.nextText();
news.setName(name);
break;
} else if ("code".equals(xp.getName())) {
String code = xp.nextText();
news.setCode(code);
break;
}
case XmlPullParser.END_TAG:
if ("news".equals(xp.getName())) {
newsList.add(news);
}
break;
default:
break;
}
// After parsing the current node, move the pointer to 1 Nodes until the node is finished and returns its event type
type = xp.next();
}
// Send a message
handler.sendEmptyMessage(1);
} catch (Exception e) {
e.printStackTrace();
}
}
You can start downloading
// Get Download Manager
DownloadManager manager =(DownloadManager)mContext.getSystemService(mContext.DOWNLOAD_SERVICE);
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
News news = newsList.get(0);
Log.i("aii", "XML: "+news.getCode()+" , apk:"+getPackageInfo(mContext));
if(Integer.valueOf(news.getCode())>Integer.valueOf(getPackageInfo(mContext))){
if(dowmCliek) {
// Open progress bar thread
isRun = true;
dowmCliek = false;
// Update APK Delete the original installation package before
DownLoadApk.fileDelete(path + "/" + mAPK);
// Create a download request
DownloadManager.Request down = new DownloadManager.Request(
Uri.parse(mWebsite));
// Set the types of networks allowed, in this case mobile networks and wifi All right
down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
// It is forbidden to send notifications, which are downloaded in the background
down.setShowRunningNotification(true);
// Do not display the download interface
down.setVisibleInDownloadsUi(true);
// Title
down.setDestinationInExternalFilesDir(mContext, null, "XXX Upgrading ...");
// Queue the download request and return to download id
downId = manager.enqueue(down);
}else{
Toast.makeText(mContext," Upgrading ...",Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(mContext," It is the latest version and does not need to be upgraded ...",Toast.LENGTH_SHORT).show();
}
}
};
Track Download Progress
// Timing task
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
if(isRun) {
Message msg = mHandler.obtainMessage();
msg.what = 1;
mHandler.sendMessage(msg);
}
}
}, 0, 100, TimeUnit.MILLISECONDS);// Delay 0 , interval 100 In milliseconds
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case 1:
//android Download Manager
DownloadManager.Query query = new DownloadManager.Query().setFilterById(downId);
Cursor cursor = manager.query(query);
if (cursor != null && cursor.moveToFirst()) {
// Query the file size directly here
long downSize = cursor.getLong(cursor.getColumnIndex(
DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
// Get the total file download size
fileTotalSize =cursor.getLong(cursor.getColumnIndex(
DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
cursor.close();
Log.w(" Print ", " Total size " + downSize);
Log.w(" Print ", " Download progress " + fileTotalSize);
if (fileTotalSize>0) {
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setMaximumFractionDigits(2);
String result = numberFormat.format((float)fileTotalSize/(float)downSize*100);
Log.w(" Print ", "downloaded size: " + result+"%");
downBtn.setText(result+"%");
}
// Download finished
if(fileTotalSize==downSize) {
isRun = false;
downBtn.setText(" Click Upgrade ");
}
}
}
return true;
}
});
Start the installation after downloading
DownloadCompleteReceiver receiver = new DownloadCompleteReceiver();
// Broadcast after downloading
class DownloadCompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){
long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if(downId!=-1) {
// Start the installation
DownLoadApk.DownId(context,downId);
dowmCliek=true;
}
}else{
Toast.makeText(context, intent.getAction()+" Download failed ", Toast.LENGTH_SHORT).show();
}
}
}
// Start the download and complete the broadcast
mContext.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Get the project package name
private static String getPackageInfo(Context context) {
PackageInfo pi = null;
try {
PackageManager pm = context.getPackageManager();
pi = pm.getPackageInfo(context.getPackageName(),
PackageManager.GET_CONFIGURATIONS);
return pi.versionCode+"";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Summarize