Android native Downloadmanager

Source: Internet
Author: User

Code:

 Public classMainactivityextendsActivity {PrivateDownloadmanager Downloadmanager;  Public Static FinalString download_folder_name = "Trinea";  Public Static FinalString download_file_name = "meilishuo.apk";  Public Static FinalString Apk_url = "http://img.meilishuo.net/css/images/AndroidShare/Meilishuo_3.6.1_10006.apk";  Public Static FinalString key_name_download_id = "Downloadid"; Private LongDownloadid = 0; PrivateCompletereceiver Completereceiver; @TargetApi (build.version_codes. Honeycomb) @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Init (); Findviewbyid (R.id.button1). Setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method StubFile folder =environment. Getexternalstoragepublicdirectory (Download_folder_name); if(!folder.exists () | | |folder.isdirectory ())                {Folder.mkdirs (); } downloadmanager.request Request=Newdownloadmanager.request (Uri.parse (Apk_url));                Request.setdestinationinexternalpublicdir (Download_folder_name, download_file_name); Request.settitle ("Beautiful Legends"); Request.setdescription ("Meilishuo Desc");                Request.setnotificationvisibility (DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); Request.setvisibleindownloadsui (false); //Request.allowscanningbymediascanner (); //request.setallowednetworktypes (DownloadManager.Request.NETWORK_WIFI); //request.setshowrunningnotification (FALSE); //request.setnotificationvisibility (DownloadManager.Request.VISIBILITY_HIDDEN); //Application/cn.trinea.download.fileRequest.setmimetype ("Application/vnd.android.package-archive"); Downloadid=Downloadmanager.enqueue (Request); /**save download ID to Preferences **/            }        }); }    Private voidinit () {//TODO auto-generated Method StubCompletereceiver =NewCompletereceiver (); /**Register Download Success Broadcast **/registerreceiver (Completereceiver,NewIntentfilter (downloadmanager.action_download_complete)); Downloadmanager=(Downloadmanager) Getsystemservice (Download_service); }    Private intGetInt (LongDownloadid, String columnName) {Downloadmanager.query Query=Newdownloadmanager.query (). Setfilterbyid (Downloadid); intresult =-1; Cursor C=NULL; Try{C=downloadmanager.query (query); if(c! =NULL&&C.movetofirst ()) {Result=C.getint (C.getcolumnindex (columnName)); }        } finally {            if(c! =NULL) {c.close (); }        }        returnresult; } @Overrideprotected voidOnDestroy () {Super. OnDestroy ();    Unregisterreceiver (Completereceiver); }    classCompletereceiverextendsBroadcastreceiver {@Override Public voidOnReceive (Context context, Intent Intent) {/*** Get the ID of download which has download success, if the ID is * my ID and it's status is Successful, then install it **/            LongCompletedownloadid =Intent.getlongextra (downloadmanager.extra_download_id,-1); if(Completedownloadid = =Downloadid) {                //If download successful, install APK//if (Downloadmanagerpro.getstatusbyid (downloadid) = =//downloadmanager.status_successful) {                if(GetInt (Downloadid, downloadmanager.column_status) = =downloadmanager.status_successful) {String Apkfilepath=NewStringBuilder (Environment. getExternalStorageDirectory (). GetAbsolutePath ()) . Append (File.separator). Append (Download_folder_name).                    Append (File.separator). Append (Download_file_name). toString ();                Install (context, apkfilepath);    }            }        }    }; /*** Install app * *@paramContext *@paramFilePath *@returnwhether apk exist*/     Public Static BooleanInstall (context context, String FilePath) {Intent i=NewIntent (Intent.action_view); File File=NewFile (FilePath); if(File! =NULL&& file.length () > 0 && file.exists () &&File.isfile ()) {I.setdataandtype (Uri.parse ("file://" +FilePath),"Application/vnd.android.package-archive");            I.addflags (Intent.flag_activity_new_task);            Context.startactivity (i); return true; }        return false; } @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true; }}

Permissions in the manifest file:

<uses-permission android:name= "Android.permission.INTERNET"/>    <uses-permission android:name= " Android.permission.ACCESS_NETWORK_STATE "/>    <uses-permission android:name=" android.permission.WRITE_ External_storage "/>    <uses-permission android:name=" Android.permission.BROADCAST_STICKY "/>    < Uses-permission android:name= "Android.permission.DOWNLOAD_WITHOUT_NOTIFICATION"/>

Android native Downloadmanager

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.