Android offline download knowledge, android offline

Source: Internet
Author: User

Android offline download knowledge, android offline

The offline download function is as follows:
1. Download Management (START and cancel download ).
2. Network judgment (wi-fi, 3G ).
3. Independent process.
4. timed and mobile phone reminders.
5. self-starting.

Select the core method for offline downloadWhen the backend runs independently, we can easily think of services, but there are the following problems: (1) if the process of the Service is the same as that of the application, after the application exits, the service restarts once. (2) If the Process and Application of the service are inconsistent, communication between processes will be troublesome. (3) If the Process and Application of the service are consistent, select IntentService, it can avoid restarting and we do not need to download multiple tasks at the same time. We can use IntentService, and IntentService has other advantages.

 

1. Download Management
Here, we cannot focus on the download details. There are many methods for online download, probably as follows:

1 /**
  2 * Download file
  3 * @param url
  4 * @param dest Download and store local files
  5 * @param append breakpoint resume
  6 * @return
  7 * @throws Exception
  8  */
  9 public long download (String url, File dest, boolean append) throws Exception {
10 // initialize variables
11 // Preparation
12 // ... ...
13
14 try {
15 // ... ...
16 while ((readSize = is.read (buffer))> 0) {
17 // Network judgment
18
19 os.write (buffer, 0, readSize);
20 os.flush ();
twenty one                  
22 // If you need to stop the download, such as cancel, jump out of the current download
twenty three             }
twenty four         }
25} finally {
26 // ... ...
27}
28 // ... ...
29}

 Note the following points:
(1) During the download process, we hope to detect the network conditions in time. For example, if we switch from Wi-Fi to 3G, we should be able to stop the download in time.
(2). When the user chooses to cancel the download, we can also stop the current download.

2. Network judgment
To obtain the current network status, we mainly divided it into wi-fi and Mobile (including 3G, GPRS). We write a tool class as follows:

1 public class NetworkUtils {
 2  
 3 public final static int NONE = 0; // No network
 4 public final static int WIFI = 1; // Wi-Fi
 5 public final static int MOBILE = 2; // 3G, GPRS
 6
 7 / **
 8 * Get current network status
 9 * @param context
10 * @return
11 * /
12 public static int getNetworkState (Context context) {
13 ConnectivityManager connManager = (ConnectivityManager) context.getSystemService (Context.CONNECTIVITY_SERVICE);
14
15 // Mobile network judgment
16 State state = connManager.getNetworkInfo (ConnectivityManager.TYPE_MOBILE) .getState ();
17 if (state == State.CONNECTED || state == State.CONNECTING) {
18 return MOBILE;
19}
20
21 // Wifi network judgment
22 state = connManager.getNetworkInfo (ConnectivityManager.TYPE_WIFI) .getState ();
23 if (state == State.CONNECTED || state == State.CONNECTING) {
24 return WIFI;
25}
26 return NONE;
27}
28}

Based on the network status, we can control the download method:
(1). When downloads are large, we are unlikely to download them in 3G scenarios, which may cause users' dislike and concern.
(2). It is also allowed when the customer confirms that the download can be performed at 3G.
Therefore, we need to set a flexible level for the download method. Based on the characteristics of offline download, we provide three solutions for users:
(1). automatically download Mobile Data
(2). automatically download only when Wi-Fi is allowed
(3). Disable download
Only automatic download is listed here, because if it is not automatic download, you can control the manual download without setting it. Of course, when traffic loss occurs, such as manual download at 3G, prompt that the user will consume a large amount of data traffic, use it with caution.

1 public class Constant {
  2 // Download network settings offline
  3 public final static int OFFLINE_MOBILE = 0;
  4 public final static int OFFLINE_WIFI = 1;
  5 public final static int OFFLINE_OFF = 3;
  6}
  7
  8 public class Global {
  9 // Set the default off state,
10 // In order to remember the user's choice next time the application starts, this value should be stored in the database when the application is first started
11 public static int OfflineNetworkSetting = Constant.OFFLINE_OFF;
12}

You can now compare the current network and offline network settings according to the rules to determine whether the offline download service is enabled.

3. Independent Process
Offline download, wherever and whenever appropriate, is performed. Currently, the mainstream approach is to establish background services.

1 public class OfflineSerivice extends Service {
2       // ... ...
3 }

(1 ). if the OfflineService process is the same as the application process by default, it will be restarted once when the application process is killed (Netease news will exit the application when downloading offline, the reason is that the download will pause for a while). If the effect is not significant, this solution is optional.
(2 ). the OfflineService process is separated from the application, for example, the application process is "cn. cnblogs. tianxia. download, the offline download service process is set to "cn. cnblogs. tianxia. download. offline ", the relationship between the Process and the application. Of course, this will bring about a new problem: inter-process communication, of course, because offline download and modules between applications are relatively independent, this problem is relatively easy to avoid.
(3 ). if the OfflineService process is consistent with the application by default, but OfflineService inherits the IntentService, restart can be avoided. This is the method mentioned in Pro Android 3 and is very easy to use, however, I am very sorry. I recently saw that I have not personally tested it and I am not afraid to try it out at work.
In theory, solution 3 is the best solution, but for personal reasons, solution 2 is selected.

1 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
2       package="com.cnblogs.download">
3     <application android:icon="@drawable/icon" android:label="@string/app_name">        
4         
5         <service android:name="cn.cnblogs.download.OfflineService" android:process="cn.cnblogs.download.offline"/>
6     </application>
7 </manifest>

4. timed download and mobile phone reminders
Automatically downloads are automatically downloaded based on user settings, but there are many automatic download methods, such as frequent update downloads and fixed point downloads (four o'clock P.M ), download interval (every 6 hours ).
Here, we choose to download every six hours.
(1) An incorrect solution is introduced here. Once we see that every six hours, it is easy to think of starting a sub-thread timer, accumulating for six hours, the sub-thread notifies the download service to start a new round of download. The idea of this solution is correct, but it ignores the sleep status of the mobile phone. This sub-thread actually stops running, the so-called 6-hour effect may never be reached, and it must be incorrect or inaccurate.
(2). Therefore, you need to use a non-sleep method: timer and broadcast receiver. We send a broadcast every six hours. The broadcast receiver notification starts offline download. (Refer to the newsrob source code and book "Pro Android 3"):

1 public class OfflineSerivice extends Service {
  2     
  3 // Time of the last successful download
  4 private long lastDownloadTime;
  5 // Omit the code ... ...
  6
  7 public static void startAlarm (Context context) {
  8 AlarmManager alarmManager = (AlarmManager) context.getSystemService ("alarm");
  9         
10 // Send broadcast to OfflineAlarmReceiver every 6 hours
11 // It can also be set to detect download conditions in 10 minutes, and judge to start downloading in OfflineAlarmRecrive, avoiding the problem of 6 hours of long download failures
12 Intent intent = new Intent (context, OfflineAlarmReceiver.class);
13
14 PendingIntent pendingIntent = PendingIntent.getBroadcast (context.getApplicationContext (), 0, intent, 0);
15 alarmManager.cancel (pendingIntent);
16 alarmManager.setRepeating (AlarmManager.RTC_WAKEUP, System.currentTimeMillis (), 3600000 * 6, pendingIntent);
17}
18}

Process start download conditions in OfflineAlarmRecriver and notify start download

vWe mentioned the thread sleep problem. We need to wake up the mobile phone during the download process and return to sleep after the download is complete. The following are two tools:
1 public static PowerManager.WakeLock wakeLock;
  2     /**
  3 * wake up service
  4 * /
  5 public static void acquireWakeLock (Context context) {
  6
  7 if (wakeLock! = Null) {
  8 return;
  9         }
10 PowerManager powerManager = (PowerManager) (context.getSystemService (Context.POWER_SERVICE));
11 wakeLock = powerManager.newWakeLock (PowerManager.PARTIAL_WAKE_LOCK, "com.cnblogs.download.OfflineService");
12 wakeLock.acquire ();
13}
14
15 / **
16 * Release wake-up service and return to sleep
17 * /
18 public static void releaseWakeLock () {
19 if (wakeLock! = Null && wakeLock.isHeld ()) {
20 wakeLock.release ();
21 wakeLock = null;
twenty two         }
twenty three     }

PowerManager. PARTIAL_WAKE_LOCK means to wake up the CPU only. At this time, it can automatically detect the network status to ensure that the Network is normal.
You need to set the permission in Mainifest. xml:

    <uses-permission android:name="android.permission.WAKE_LOCK" />

Then, enable the reminder status in onStartConmmand () of the download service, and then release the reminder status after the download is complete:

1 @Override
2 public int onStartCommand (Intent intent, int flags, int startId) {
3 acquireWakeLock (OfflineService.this);
4 // Omit the code ...
5 return super.onStartCommand (intent, flags, startId);
6}

5. self-starting
To make the code clearer, we need to define a self-starting aggreger:

1 /**
  2 * Self-start offline download service
  3 * @author user
  4 * /
  5 public class OfflineReceiver extends BroadcastReceiver {
  6 @Override
  7 public void onReceive (Context context, Intent arg1) {
  8 // Start timer
  9 OfflineService.startAlarm (context);
10}
11}
12 Register this receiver in AndroidManifest.xml, as follows:
13
14 <receiver android: name = "cn.cnblogs.download.OfflineReceiver">
15 <intent-filter>
16 <!-Self-starting->
17 <action android: name = "android.intent.action.BOOT_COMPLETED" />
18 <category android: name = "android.intent.category.HOME" />
19 </ intent-filter>
20 </ receiver> 

In this way, you can start the broadcast and start the timer at startup.

6. Summary
For simplicity and clarity, this article only lists the most important links for offline downloads. for cleanup policies, manual and automatic modes, and page jumps, uidesign and business requirements are not too much involved, but these things often take a lot of time and require a lot of detail accumulation and patient debugging. The only thing we need to do is to constantly improve!

 


Android offline game download URL

For the URL, there are a lot of resources in the market of Apsara stack. In fact, as long as you connect to the 360 mobile assistant or pods, and 91 assistant, there are a lot of game and software resources. Convenient
 
How to download an offline map from an Android phone

You can simply open the mobile phone map home page of Baidu (or sogou, or sousuo, or AMAP) and download the android map software for your mobile phone, you can view the offline map introduction or help. Generally, you can directly copy the downloaded map data to the corresponding folder on the SD card or SD card, open the mobile phone map software, and prompt that the offline import is successful.

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.