Android updates the notification bar with a progress bar and android progress bar

Source: Internet
Author: User

Android updates the notification bar with a progress bar and android progress bar

After checking the information on the Internet, the Android version update notification bar contains a progress bar, which is drunk and basically copied. Some codes are incomplete, even the source code is not downloaded, and points are required for downloading, it's so dark !! I have also written a Notification in the Custom Notification bar before. I want to write it myself.

Because you need to access the network to download an update in the notification bar, a service is written and an update is downloaded in the service.

First look at the MainActivity code:

Package com. wsj. wsjdemo; import android. OS. bundle; import android. app. activity; import android. app. alertDialog; import android. content. dialogInterface; import android. content. intent; import android. view. menu; public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); initGlobal (); checkVersion () ;}/ *** initialize the global variable * in actual work, serverVersion is obtained from the server, it is best to execute */public void initGlobal () {try {Global. localVersion = getPackageManager (). getPackageInfo (getPackageName (), 0 ). versionCode; // set the local version Global. serverVersion = 2; // assume that the server version is 2 and the local version is 1} catch (Exception ex) {ex. printStackTrace () ;}}/*** check the updated version */public void checkVersion () {if (Global. localVersion <Global. serverVersion) {// when a new version is found, the user is prompted to update AlertDialog. builder alert = new AlertDialog. builder (this); alert. setTitle ("software upgrade "). setMessage ("A new version is found. We recommend that you update it now. "). setPositiveButton ("Update", new DialogInterface. onClickListener () {public void onClick (DialogInterface Diener, int which) {// enable the update Service UpdateService // to better modularize update, you can upload updateService dependent values // such as layout ID, resource ID, and dynamically obtained title. Here we use app_name as an example: Intent updateIntent = new Intent (MainActivity. this, UpdateService. class); updateIntent. putExtra ("app_name", R. string. app_name); updateIntent. putExtra ("downurl", "http://www.subangloan.com/Contract/App/Android/caijia_unsign_signed.apk"); startService (updateIntent );}}). setNegativeButton ("cancel", new DialogInterface. onClickListener () {public void onClick (DialogInterface diich, int which) {dialog. dismiss () ;}}); alert. create (). show ();} else {// cleanup, skip // cheanUpdateFile (), and I will attach the code later }}}

Activity_main.xml file: nothing is a simple interface

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" /></LinearLayout>

Global. java used in Main

Package com. wsj. wsjdemo; public class Global {// version information public static int localVersion = 0; public static int serverVersion = 0; public static String downloadDir = "app/download /";}

UpdateService. java

Package com. wsj. wsjdemo; import java. io. file; import java. io. IOException; import java. text. decimalFormat; import com. lidroid. xutils. httpUtils; import com. lidroid. xutils. exception. httpException; import com. lidroid. xutils. http. responseInfo; import com. lidroid. xutils. http. callback. requestCallBack; import android. app. notification; import android. app. icationicationmanager; import android. app. pendingIntent; import Droid. 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. widget. remoteViews; public class UpdateService extends Service {private static String down_url; // = "http: // 192.168.1.112: 8080/360. apk "; private static final int DOWN_ OK = 1; // private static final int downloaded DOWN_ERROR = 0; private String app_name; private icationicationmanager icationmanager; private Notification notification; private Intent updateIntent; private PendingIntent pendingIntent; private String updateFile; private int icationication_id = 0; long totalSize = 0; // total file size/*** update UI */final Handler handler = new Handler () {@ SuppressWarnings ("deprecation") @ Overridepublic void handleMessage (Message m Sg) {switch (msg. what) {case DOWN_ OK: // download complete. Click to install Intent installApkIntent = getFileIntent (new File (updateFile); pendingIntent = PendingIntent. getActivity (UpdateService. this, 0, installApkIntent, 0); notification. contentIntent = pendingIntent; notification. flags | = Notification. FLAG_AUTO_CANCEL; notification. setLatestEventInfo (UpdateService. this, app_name, "Download succeeded, click to install", pendingIntent); icationicationmanage R. Y (ication_id _id, notification); stopService (updateIntent); break; case DOWN_ERROR: notification. setLatestEventInfo (UpdateService. this, app_name, "Download failed", pendingIntent); break; default: stopService (updateIntent); break ;}};@ Overridepublic IBinder onBind (Intent arg0) {return null ;} @ Overridepublic int onStartCommand (Intent intent, int flags, int startId) {if (intent! = Null) {try {app_name = intent. getStringExtra ("app_name"); down_url = intent. getStringExtra ("downurl"); // create the File updateFile = FileUtils. getDiskCacheDir (getApplicationContext (), "xxxx.apk"); if (! UpdateFile. exists () {try {updateFile. createNewFile ();} catch (IOException e) {e. printStackTrace () ;}/// create notification createNotification (); // start downloadUpdateFile (down_url, updateFile. getAbsolutePath ();} catch (Exception e) {e. printStackTrace () ;}} return super. onStartCommand (intent, flags, startId);}/***** create a notification bar */RemoteViews contentView; @ SuppressWarnings ("deprecation") public void createNotification () {icationicationmanager = (icationicationmanager) getSystemService (Context. NOTIFICATION_SERVICE); notification = new Notification (); notification. icon = R. drawable. ic_launcher; // this parameter is the value that indicates the flash of the notification. notification. tickerText = "Start download"; // pendingIntent = PendingIntent. getActivity (this, 0, updateIntent, 0); // The following parameters are the notification content displayed in the view bar. setLatestEventInfo (this, app_name, "downloaded: 0%", pendingIntent); // icationicationmanager. Y (ication_id _id, notification);/*** here we use a custom view to display Notification */contentView = new RemoteViews (getPackageName (), R. layout. notification_item); contentView. setTextViewText (R. id. notificationTitle, "downloading"); contentView. setTextViewText (R. id. icationicationpercent, "0%"); contentView. setProgressBar (R. id. icationicationss, 100, 0, false); notification. contentView = contentView; updateIntent = new Intent (this, MainActivity. class); updateIntent. addFlags (Intent. FLAG_ACTIVITY_SINGLE_TOP); pendingIntent = PendingIntent. getActivity (this, 0, updateIntent, 0); notification. contentIntent = pendingIntent; icationicationmanager. Y (ication_id _id, notification);}/***** download file */public void downloadUpdateFile (String down_url, String file) throws Exception {updateFile = file; httpUtils = new HttpUtils (); HttpUtils. download (down_url, file, new RequestCallBack <File> () {@ Overridepublic void onSuccess (ResponseInfo <File> responseInfo) {// Message message = handler. obtainMessage (); message. what = DOWN_ OK; handler. sendMessage (message); installApk (new File (updateFile), UpdateService. this) ;}@ Overridepublic void onFailure (HttpException error, String msg) {Message message = handler. obtainMessage (); message. what = DOWN_ERROR; handler. sendMessage (message) ;}@ Overridepublic void onLoading (long total, long current, boolean isUploading) {super. onLoading (total, current, isUploading); double x_double = current * 1.0; double tempresult = x_double/total; DecimalFormat df1 = new DecimalFormat ("0.00 ");//##. 00% // percent format, followed by less than two digits with 0 fill String result = df1.format (tempresult); contentView. setTextViewText (R. id. icationicationpercent, (int) (Float. parseFloat (result) * 100) + "%"); contentView. setProgressBar (R. id. icationicationss, 100, (int) (Float. parseFloat (result) * 100), false); icationicationmanager. Y (ication_id _id, notification) ;}}) ;}// after the download is complete, open the apk installation page public static void installApk (File file, Context context) {// L. I ("msg", "Path of the installation package for obtaining the SD card through version update =" + file. getAbsolutePath (); Intent openFile = getFileIntent (file); context. startActivity (openFile);} public static Intent getFileIntent (File file) {Uri uri = Uri. fromFile (file); String type = getMIMEType (file); Intent intent = new Intent ("android. intent. action. VIEW "); intent. addCategory ("android. intent. category. DEFAULT "); intent. addFlags (Intent. FLAG_ACTIVITY_NEW_TASK); intent. setDataAndType (uri, type); return intent;} public static String getMIMEType (File f) {String type = ""; String fName = f. getName (); // get the extension String end = fName. substring (fName. lastIndexOf (". ") + 1, fName. length (); if (end. equals ("apk") {type = "application/vnd. android. package-archive ";} else {// * If you cannot open the package directly, you can jump out of the Software List and select */type =" */* ";} return type ;}}

Basically, annotations are clearly written, which uses the Xutils open-source framework to download files.

If you think it is difficult to see it, click Download demo without points. If you think it is good, I hope to give a comment at the bottom of the article. This is also my option. Thank you.


Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

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.