Android App Automatic Update Notification Bar Download

  • 2021-09-12 02:11:25
  • OfStack

This article example for everyone to share Android App automatic update notification bar download specific code, for your reference, the specific content is as follows

Version update instructions

There is a call to UpdateService startup service to check the download installation package and so on

1. Download the file and write it to sdcard after downloading

2. How to display download progress on the notification bar

3. Install automatically after downloading

4. How to determine if there is a new version

Main class for version update


package com.wei.update; 
 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.URL; 
import java.util.HashMap; 
import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import org.json.JSONException; 
import org.json.JSONObject; 
import org.w3c.dom.Document; 
import org.w3c.dom.Element; 
import org.w3c.dom.Node; 
import org.w3c.dom.NodeList; 
import org.xmlpull.v1.XmlPullParser; 
import org.xmlpull.v1.XmlPullParserException; 
import org.xmlpull.v1.XmlPullParserFactory; 
 
import com.wei.util.MyApplication; 
 
 
import android.app.AlertDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.content.pm.PackageManager.NameNotFoundException; 
import android.os.Handler; 
 
/** 
 *  Version update main class , There is a call here UpdateService Start the service to check and download the installation package, etc.  1.  Download the file and write it to sdcard 2.  How to Display Download Progress on the Notification Bar  
 * 3.  Automatic installation after downloading  4.  How to determine if there is a new version  
 * 
 * @author david 
 */ 
public class UpdateManager { 
 private static String packageName;// = "com.yipinzhe"; //  Package name applied  
 private static String jsonUrl = "version.txt"; // JSON Version file URL 
 private static String xmlUrl = "version.xml"; // XML Version file URL 
 private static final String DOWNLOAD_DIR = "/"; //  Subdirectories saved after application download  
 
 private Context mContext; 
 HashMap<String, String> mHashMap;//  Save the parsed XML Information  
 int versionCode, isNew; 
 
 public UpdateManager(Context context) { 
 this.mContext = context; 
 packageName = context.getPackageName(); 
 jsonUrl = MyApplication.site + jsonUrl; 
 xmlUrl = MyApplication.site + xmlUrl; 
 checkVersion(); 
 } 
 
 Handler checkHandler = new Handler() { 
 @Override 
 public void handleMessage(android.os.Message msg) { 
 if (msg.what == 1) { 
 //  When a new version is found, prompt the user for update  
 StringBuffer message = new StringBuffer(); 
 message.append(mHashMap.get("note").replace("|", "\n")); 
 AlertDialog.Builder alert = new AlertDialog.Builder(mContext); 
 alert.setTitle(" Software upgrade ") 
  .setMessage(message.toString()) 
  .setPositiveButton(" Update ", 
  new DialogInterface.OnClickListener() { 
   @Override 
   public void onClick(DialogInterface dialog, 
   int which) { 
   //  Turn on the update service UpdateService 
   System.out.println(" You clicked on Update "); 
   Intent updateIntent = new Intent( 
   mContext, UpdateService.class); 
   /** 
   * updateIntent.putExtra("downloadDir", 
   * DOWNLOAD_DIR); 
   * updateIntent.putExtra("apkUrl", 
   * mHashMap.get("url")); 
   */ 
   mContext.startService(updateIntent); 
   } 
  }) 
  .setNegativeButton(" Cancel ", 
  new DialogInterface.OnClickListener() { 
   @Override 
   public void onClick(DialogInterface dialog, 
   int which) { 
   dialog.dismiss(); 
   } 
  }); 
 alert.create().show(); 
 } 
 }; 
 }; 
 
 /** 
 * Check whether there is a new version  
 */ 
 public void checkVersion() { 
 try { 
 //  Get the software version number , Correspondence AndroidManifest.xml Under android:versionCode 
 versionCode = mContext.getPackageManager().getPackageInfo( 
  packageName, 0).versionCode; 
 } catch (NameNotFoundException e) { 
 e.printStackTrace(); 
 } 
 
 new Thread() { 
 @Override 
 public void run() { 
 String result = null; 
 /** 
  * try { // If the server side is JSON Text file  result = 
  * MyApplication.handleGet(jsonUrl); if (result != null) { 
  * mHashMap = parseJSON(result); } } catch (Exception e1) { 
  * e1.printStackTrace(); } 
  */ 
 
 InputStream inStream = null; 
 try { 
  //  Native machine XML Documents  
  inStream = UpdateManager.class.getClassLoader().getResourceAsStream("version.xml"); 
  //  If the server side is XML Documents  
  inStream = new URL(xmlUrl).openConnection().getInputStream(); 
  if (inStream != null) 
  mHashMap = parseXml(inStream); 
 } catch (Exception e1) { 
  e1.printStackTrace(); 
 } 
 if (mHashMap != null) { 
  int serviceCode = Integer.valueOf(mHashMap.get("version")); 
  if (serviceCode > versionCode) {//  Version judgment , Return true There is a new version  
  isNew = 1; 
  } 
 } 
 checkHandler.sendEmptyMessage(isNew); 
 }; 
 }.start(); 
 } 
 
 /** 
 * Parsing server-side JSON Version file  
 */ 
 public HashMap<String, String> parseJSON(String str) { 
 HashMap<String, String> hashMap = new HashMap<String, String>(); 
 try { 
 JSONObject obj = new JSONObject(str); 
 hashMap.put("version", obj.getString("version")); 
 hashMap.put("name", obj.getString("name")); 
 hashMap.put("url", obj.getString("url")); 
 hashMap.put("note", obj.getString("note")); 
 } catch (JSONException e) { 
 e.printStackTrace(); 
 } 
 return hashMap; 
 } 
 
 /** 
 * Parsing server-side XML Version file  
 */ 
 public HashMap<String, String> parseXml(InputStream inputStream) { 
 HashMap<String, String> hashMap = new HashMap<String, String>(); 
 try { 
 XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser(); 
 parser.setInput(inputStream, "GBK");// Setting data source encoding  
 int eventCode = parser.getEventType();// Get the event type  
 while(eventCode != XmlPullParser.END_DOCUMENT) { 
 System.out.println(" Loop start "); 
 switch (eventCode){ 
  case XmlPullParser.START_DOCUMENT: // Start reading XML Document  
  System.out.println("START_DOCUMENT"); 
  break; 
  case XmlPullParser.START_TAG:// Start reading a tag  
  if("version".equals(parser.getName())) { 
  hashMap.put(parser.getName(), parser.nextText()); 
  } else if("name".equals(parser.getName())) { 
  hashMap.put(parser.getName(), parser.nextText()); 
  } else if("url".equals(parser.getName())) { 
  hashMap.put(parser.getName(), parser.nextText()); 
  } else if("note".equals(parser.getName())) { 
  hashMap.put(parser.getName(), parser.nextText()); 
  } 
  break; 
  case XmlPullParser.END_TAG: 
  break; 
 } 
 eventCode = parser.next();// Continue to read under 1 Element nodes and get the event code  
  
 } 
 System.out.println(hashMap.get("version")); 
 } catch(Exception e) { 
 
 } 
 return hashMap; 
 
 
 /**
 *try { 
 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
 DocumentBuilder builder = factory.newDocumentBuilder(); 
 Document document = builder.parse(inStream); 
 Element root = document.getDocumentElement();// Get the root node  
 NodeList childNodes = root.getChildNodes();// Get all child nodes , Then traverse  
 for (int j = 0; j < childNodes.getLength(); j++) { 
 Node childNode = childNodes.item(j); 
 if (childNode.getNodeType() == Node.ELEMENT_NODE) { 
  Element childElement = (Element) childNode; 
  if ("version".equals(childElement.getNodeName())) { 
  hashMap.put("version", childElement.getFirstChild() 
  .getNodeValue()); 
  } 
  else if (("name".equals(childElement.getNodeName()))) { 
  hashMap.put("name", childElement.getFirstChild() 
  .getNodeValue()); 
  } 
  else if (("url".equals(childElement.getNodeName()))) { 
  hashMap.put("url", childElement.getFirstChild() 
  .getNodeValue()); 
  } else if (("note".equals(childElement.getNodeName()))) { 
  hashMap.put("note", childElement.getFirstChild() 
  .getNodeValue()); 
  } 
 } 
 } 
 } catch (Exception e) { 
 e.printStackTrace(); 
 }*/ 
 
 } 
} 

Service class with updated version


package com.wei.update; 
 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 
 
import com.wei.util.MyApplication; 
import com.wei.wotao.R; 
 
//import android.annotation.SuppressLint; 
import android.app.Notification; 
import android.app.NotificationManager; 
import android.app.PendingIntent; 
import android.app.Service; 
import android.content.Intent; 
import android.net.Uri; 
import android.os.Environment; 
import android.os.Handler; 
import android.os.IBinder; 
import android.os.Message; 
import android.view.View; 
import android.widget.RemoteViews; 
 
/** 
 *  Download the service class of the installation package  
 * @author david 
 */ 
 
public class UpdateService extends Service { 
 
 //  File storage  
 private File saveDir; 
 private File saveFile; 
 private String apkUrl; 
 
 //  Notification column  
 private NotificationManager updateNotificationManager = null; 
 private Notification updateNotification = null; 
 
 //  Notification bar jump Intent 
 private Intent updateIntent = null; 
 private PendingIntent updatePendingIntent = null; 
 
 //  Download status  
 private final static int DOWNLOAD_COMPLETE = 0; 
 private final static int DOWNLOAD_FAIL = 1; 
 
 private RemoteViews contentView; 
 
 @Override 
 public int onStartCommand(Intent intent, int flags, int startId) { 
 System.out.println("onStartCommand"); 
 contentView = new RemoteViews(getPackageName(), R.layout.activity_app_update); 
 //  Get value pass  
 String downloadDir = intent.getStringExtra("downloadDir"); 
 apkUrl = MyApplication.site+intent.getStringExtra("apkUrl"); 
 //  If there is SD Card , Is created APK Documents  
 if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment 
 .getExternalStorageState())) { 
 
 saveDir = new File(Environment.getExternalStorageDirectory(), 
  downloadDir); 
 saveFile = new File(saveDir.getPath(), getResources() 
  .getString(R.string.app_name) + ".apk"); 
 } 
 
 this.updateNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
 this.updateNotification = new Notification(); 
 
 //  In the process of setting download, click the notification bar to return to the main interface  
 updateIntent = new Intent(); 
 updatePendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0); 
 //  Set the display content of the notification bar  
 updateNotification.icon = R.drawable.icon_info; 
 updateNotification.tickerText = " Start downloading "; 
 updateNotification.contentView.setProgressBar(R.id.progressBar1, 100, 0, true); 
 updateNotification.setLatestEventInfo(this, 
 getResources().getString(R.string.app_name), "0%", 
 updatePendingIntent); 
 //  Issue a notice  
 updateNotificationManager.notify(0, updateNotification); 
 new Thread(new DownloadThread()).start(); 
 return super.onStartCommand(intent, flags, startId); 
 } 
 
 @Override 
 public IBinder onBind(Intent intent) { 
 return null; 
 } 
 
 /** 
 * Download thread  
 */ 
 private class DownloadThread implements Runnable { 
 Message message = updateHandler.obtainMessage(); 
 
 public void run() { 
 message.what = DOWNLOAD_COMPLETE; 
 if (saveDir!=null && !saveDir.exists()) { 
 saveDir.mkdirs(); 
 } 
 if (saveFile!=null && !saveFile.exists()) { 
 try { 
  saveFile.createNewFile(); 
 } catch (IOException e) { 
  e.printStackTrace(); 
 } 
 } 
 try { 
 long downloadSize = downloadFile(apkUrl, saveFile); 
 if (downloadSize > 0) {//  Download succeeded  
  updateHandler.sendMessage(message); 
 } 
 } catch (Exception ex) { 
 ex.printStackTrace(); 
 message.what = DOWNLOAD_FAIL; 
 updateHandler.sendMessage(message);//  Download failed  
 } 
 } 
 
 public long downloadFile(String downloadUrl, File saveFile) 
 throws Exception { 
 int downloadCount = 0; 
 int currentSize = 0; 
 long totalSize = 0; 
 int updateTotalSize = 0; 
 int rate = 0;//  Download completion ratio  
 
 HttpURLConnection httpConnection = null; 
 InputStream is = null; 
 FileOutputStream fos = null; 
 
 try { 
 URL url = new URL(downloadUrl); 
 httpConnection = (HttpURLConnection) url.openConnection(); 
 httpConnection.setRequestProperty("User-Agent", 
  "PacificHttpClient"); 
 if (currentSize > 0) { 
  httpConnection.setRequestProperty("RANGE", "bytes=" 
  + currentSize + "-"); 
 } 
 httpConnection.setConnectTimeout(200000); 
 httpConnection.setReadTimeout(200000); 
 updateTotalSize = httpConnection.getContentLength();// Get the file size  
 if (httpConnection.getResponseCode() == 404) { 
  throw new Exception("fail!"); 
 } 
 is = httpConnection.getInputStream(); 
 fos = new FileOutputStream(saveFile, false); 
 byte buffer[] = new byte[1024 * 1024 * 3]; 
 int readsize = 0; 
 while ((readsize = is.read(buffer)) != -1) { 
  fos.write(buffer, 0, readsize); 
  
  totalSize += readsize;// Number of bytes downloaded  
  rate = (int) (totalSize * 100 / updateTotalSize);// Current download progress  
  //  In order to prevent the application from being tight due to frequent notifications, the percentage increased 10 Notify 1 Times  
  if ((downloadCount == 0) || rate - 0 > downloadCount) { 
  downloadCount += 1; 
  updateNotification.setLatestEventInfo( 
  UpdateService.this, " Downloading ", rate + "%", 
  updatePendingIntent);// Set the content, title, and so on of the notification  
  updateNotification.contentView.setProgressBar(R.id.progressBar1, 100, rate, true); 
  updateNotificationManager.notify(0, updateNotification);// Publish the notice  
  } 
  
  
  
 } 
 } finally { 
 if (httpConnection != null) { 
  httpConnection.disconnect(); 
 } 
 if (is != null) { 
  is.close(); 
 } 
 if (fos != null) { 
  fos.close(); 
 } 
 } 
 return totalSize; 
 } 
 } 
 
 private Handler updateHandler = new Handler() { 
 @Override 
 public void handleMessage(Message msg) { 
 switch (msg.what) { 
 case DOWNLOAD_COMPLETE: 
 // Automatically install when downloading is finished APK(ps, Make a phone call   Start-up interface for sending short messages ) 
 Uri uri = Uri.fromFile(saveFile);// According to File Get the resource locator of the installation package  
 Intent installIntent = new Intent(Intent.ACTION_VIEW);// Settings Action 
 installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// New Activity Will be in 1 A new task is opened instead of the original task stack  
 installIntent.setDataAndType(uri, "application/vnd.android.package-archive");// Settings URI Data type of  
 startActivity(installIntent);// Put the packed Intent Pass to startActivity 
  
 // When the download is complete, update the notification bar, and when the notification bar is clicked, install APK 
 updatePendingIntent = PendingIntent.getActivity(UpdateService.this, 0, installIntent, 0); 
 updateNotification.defaults = Notification.DEFAULT_SOUND;//  Ringtone reminder  
 updateNotification.setLatestEventInfo(UpdateService.this, getResources().getString(R.string.app_name), 
  " Download complete , Click Install ", updatePendingIntent); 
 updateNotificationManager.notify(0, updateNotification); 
 
 //  Stop service  
 stopService(updateIntent); 
 break; 
 case DOWNLOAD_FAIL: 
 //  Download failed  
 updateNotification.setLatestEventInfo(UpdateService.this, 
  getResources().getString(R.string.app_name), 
  " Download failed , Network connection timeout ", updatePendingIntent); 
 updateNotificationManager.notify(0, updateNotification); 
 break; 
 default: 
 stopService(updateIntent); 
 break; 
 } 
 } 
 }; 
} 

Related articles: