Android Update upgrade Download custom updates version

Source: Internet
Author: User

Android Update module custom update


This summary is written because of a bug in the project that is compatible with the Android system
The Android project was originally using an API-provided download methodas follows:
Downloadmanager Downloadmanager = (downloadmanager) getsystemservice (activity.download_service);D Ownloadmanager.request request = new request (Uri.parse (DL)); Request.settitle (GetString (r.string.app_name)); Request.setdestinationuri (Getdownloadname (Getintent () Getstringextra ("Version_name")); Long reference = Downloadmanager.enqueue (Request); Usersettinghelper.getinstance (). Setupgradekey (reference);


However, such as Samsung Huawei and other mobile phones its own system to remove the Google services so as to cause a crash

find the information on the Internet and change it. Finally fix the bug quickly:
1) Main activity
Package Com.example.updataapk;import Android.app.activity;import Android.content.intent;import Android.net.Uri; Import Android.os.bundle;import android.view.view;import android.view.view.onclicklistener;/** * * @author Baozi * */PU Blic class Mainactivity extends Activity {//address private String DL = "http://17shihui.cn/download/shihui.apk"; @ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); Function_utility.setappcontext (Getapplicationcontext ()); Findviewbyid (R.id.button1). SetOnClickListener (New Onclicklistener () {@Overridepublic void OnClick (View v) {uri uri = uri.parse (DL); Intent Intent = new Intent (intent.action_ VIEW, URI); startactivity (intent);}}); Findviewbyid (R.id.button2). Setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {try { Download (DL);} catch (Exception e) {e.printstacktrace ();}}});} private void Download (String dl) throws Exception {if (Android.os.Build.VERSION.SDK_INT >= Android.os.Build.VERSION_CODES. Gingerbread) {Intent service = new Intent (this, downloadservice.class); Service.putextra (Downloadservice.intent_url, DL); StartService (service);} else {Intent Intent = new Intent (Intent.action_view, Uri.parse (DL)); startactivity (Intent);}}}


2) Download module
Package Com.example.updataapk;import Java.io.file;import Java.io.fileoutputstream;import java.io.InputStream; Import Java.net.httpurlconnection;import Java.net.url;import Android.app.notification;import Android.app.notificationmanager;import Android.app.pendingintent;import Android.app.service;import Android.content.context;import Android.content.intent;import Android.net.uri;import Android.os.Handler;import Android.os.ibinder;import Android.os.message;import Android.util.log;import Android.widget.remoteviews;public Class Downloadservice extends Service {//Notification name private String notify_name = "apk downloading ...";p ublic static final Str ing intent_url = "URL";p rivate Context mcontext = this; Notification mnotification;private static final int notify_id = 0;private Notificationmanager mnotificationmanager;/* Download package installation path */private static final String savepath = Function_utility.getupgradepath ();p rivate static final string Savefilena me = Savepath + "demo.apk";p rivate String apkurl;private int PROgress;boolean canceled;private Thread downloadthread; @Overridepublic ibinder onbind (Intent Intent) {return null;} @Overridepublic void OnCreate () {super.oncreate (); Mnotificationmanager = (Notificationmanager) getsystemservice ( Android.content.Context.NOTIFICATION_SERVICE);}  public int Onstartcommand (Intent Intent, int flags, int startid) {log.i ("Downloadservice", "intent=" + intent.tostring () +           " ;    Flags= "+ Flags +"; Startid "+ Startid)" if (Intent.hasextra (Downloadservice.intent_url)) {Apkurl = (String) Intent.getextras (). Get ( Downloadservice.intent_url);} progress = 0;setupnotification (); new Thread () {public void run () {//Start download startdownload ();};}. Start (); return startid;}; private void Startdownload () {canceled = false;downloadapk ();} Private Handler Mhandler = new Handler () {@Overridepublic void Handlemessage (Message msg) {super.handlemessage (msg); Switch (msg.what) {case 0://Download complete//Cancel notification mnotificationmanager.cancel (notify_id); installapk (); Break;case 2:// This is a manual cancellation of the user interface, so it passes the ActIvity OnDestroy (); method//Cancel Notification mnotificationmanager.cancel (notify_id); break;case 1:int rate = msg.arg1;if (Rate < 100) { Remoteviews Contentview = Mnotification.contentview;contentview.settextviewtext (R.id.tv_progress, rate + "%"); Contentview.setprogressbar (R.id.progressbar, +, rate, false);} else {//after downloading the change notification form mnotification.flags = Notification.flag_auto_cancel;mnotification.contentview = null; Mnotification.setlatesteventinfo (Mcontext, "Download Done", "file downloaded", null); Stopself ();//stop service itself}pendingintent ContentIntent2 = Pendingintent.getactivity (Getapplicationcontext (), 0, New Intent (), Pendingintent.flag_update_ current); mnotification.contentintent = Contentintent2;mnotificationmanager.notify (notify_id, mNotification); ; case 3:mnotification.flags = Notification.flag_auto_cancel; Remoteviews Contentview = new Remoteviews (Getpackagename (), r.layout.update_download_notification_layout); Contentview.settextviewtext (r.id.name, "Download Failed");//Specify personalization View Mnotification.contentview = contentview;intent inteNT = new Intent (Getapplicationcontext (), mainactivity.class); Pendingintent contentintent = pendingintent.getactivity (Getapplicationcontext (), 0, intent, pendingintent.flag_ update_current);//specify content Intent Mnotification.contentintent = contentintent;mnotificationmanager.notify (NOTIFY_ID, mnotification); stopself ();//stop service itself break;}}};/ * * Install apk * * @param url */private void installapk () {File apkfile = new File (savefilename); if (!apkfile.exists ()) {Retu RN;} Intent i = new Intent (Intent.action_view); I.setflags (Intent.flag_activity_new_task); I.setdataandtype (Uri.parse (" file://"+ apkfile.tostring ())," application/vnd.android.package-archive "); mcontext.startactivity (i);} private int lastrate = 0;private InputStream is = null;private FileOutputStream fos = null;/** * Download apk * * @param URL */p rivate void downloadapk () {downloadthread = new Thread (mdownapkrunnable);d Ownloadthread.start ();} Private Runnable mdownapkrunnable = new Runnable () {@Overridepublic void run () {try {URL url = new URL (apkurl); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.connect (); int length = Conn.getcontentlength (); is = Conn.getinputstream (); File File = new file (Savepath), if (!file.exists ()) {file.mkdirs ();} String apkfile = savefilename; File Apkfile = new file (apkfile); fos = new FileOutputStream (apkfile); int count = 0;byte buf[] = new byte[1024];d o {int num Read = Is.read (BUF); count + = Numread;progress = (int) (((float) count/length) * 100);//update progress message msg = Mhandler.obtai Nmessage (); msg.what = 1;msg.arg1 = progress;if (Progress >= lastrate + 1) {mhandler.sendmessage (msg); lastrate = Progres s;} if (numread <= 0) {mhandler.sendemptymessage (0);//download complete notification installation//download finished, cancelled also set canceled = True;break;} Fos.write (buf, 0, numread);} while (!canceled);//Click Cancel to stop the download. LOG.I ("Downloadservice----------Canceled", Canceled + ""); Fos.close (); Is.close ();} catch (Exception e) {Message msg = Mhandler.obtainmessage (); msg.what = 3;mhandler.sendmessage (msg); E.printstacktrace () ;} Finally {try {if (FOS!= null) {Fos.close ();} Is.close (); if (is = = null) {Is.close ();}} catch (Exception e) {e.printstacktrace ();}}}};/ * * Create notification */private void Setupnotification () {int icon = R.drawable.ic_launcher; Charsequence tickertext = "Start download"; Long when = System.currenttimemillis (); mnotification = new Notification (icon, Tickertext, when);; /placed in "running" column mnotification.flags = notification.flag_ongoing_event; Remoteviews Contentview = new Remoteviews (Getpackagename (), r.layout.update_download_notification_layout); Contentview.settextviewtext (R.id.name, notify_name);//Specify personalization view Mnotification.contentview = Contentview; Pendingintent contentintent = pendingintent.getactivity (this, 0, New Intent (), pendingintent.flag_update_current);// Specify content Intent Mnotification.contentintent = contentintent;mnotificationmanager.notify (notify_id, mNotification);}}

3) Download the address to your phone
Package Com.example.updataapk;import Java.io.file;import Java.io.ioexception;import Android.annotation.suppresslint;import android.content.context;import android.os.Environment; @SuppressWarnings (" Deprecation ") @SuppressLint ({" Defaultlocale "," SimpleDateFormat "}) public class Function_utility {private static Context mappcontext;public static void Setappcontext (context context) {Mappcontext = context;} public static Context Getappcontext () {return mappcontext;} /** * Download to SD card address */public static string Getupgradepath () {String filePath = Getapprootpath () + "/upgrade/"; File File = new file (FilePath), if (!file.isdirectory ()) {file.mkdirs ();} File = Null;return FilePath;} public static string Getapprootpath () {String filePath = "/weimicommunity"; if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {FilePath = Environment.getexternalstoragedirectory () + FilePath;} else {FilePath = Getappcontext (). Getcachedir () + FilePath;} File File = new file (FilePath); if (!file.exists ()) {fiLe.mkdirs ();} FILE = null; File Nomedia = new file (FilePath + "/.nomedia"), if (!nomedia.exists ()) try {nomedia.createnewfile ();} catch (IOException E ) {e.printstacktrace ();} return filePath;}}

4) Androidmanifest.xml
<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/        Android "package=" com.example.updataapk "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkversion= "8" android:targetsdkversion= "/> <uses-permission android:name=" android.pe Rmission. INTERNET "/> <uses-permission android:name=" Android.permission.WRITE_EXTERNAL_STORAGE "/> <uses-permiss         Ion Android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <application android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/apptheme "> <activity android:name=" com.example.updataapk.MainActivity "android:label=" @string/                App_name "> <intent-filter> <action android:name=" Android.intent.action.MAIN "/> <category andRoid:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> <s Ervice android:name= "Com.example.updataapk.DownloadService" > </service> </application></manif Est>

:

automatic installation After download is complete

Android Update upgrade Download custom updates version

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.