Device storage monitoring for Android Service

Source: Internet
Author: User

Http://cache.baiducontent.com/C? M = queue & P = c665c54ad6c24ac30be29f28174f82 & newp = queue & User = Baidu & fm = SC & query = storage + space + running + out & qid = & p1 = 1

In the process of being responsible for the file system module, problems often occur due to the system space consumption. Therefore, ensure that a certain amount of space is reserved for system functions (such as Database Synchronization. Generally, function machines are reserved by file system modules. In Android, how does one manage and monitor device buckets?

If you have experienced filling up or about to filling up memory when using Android phones, you may notice that in this case, the mobile phone's notifications bar will have"StorageSpaceRunningOut. When you click this notification, you will find setting->Storage
The following message is displayed in settings-> device memory: not enough.Storage space.

This service is implemented in Android/framework/base/services/Java/COM/Android/Server/devicestoragemonitorservice. java. The devicestoragemonitorservice class provides a service that monitors the storage space on a device. If the remaining storage space of the device is smaller than a threshold value (10% of the storage space by default, this value can be set), a warning will be sent to the user indicating that the remaining space is insufficient, let users release some space.

Next we will analyze this class. First, let's take a look at how the service is added. Use servicemanager. addservice () in Android/frameworks/base/services/Java/COM/Android/Server/systemserver. Java to add system services:

Add the DSMs service to systemserver:
1
2
3
4
5
6
7
  Try {
Slog. I (TAG, "DeviceStorageMonitor ");
Servicemanager. addservice (devicestoragemonitorservice. Service,
New devicestoragemonitorservice (context ));
} Catch (throwable e ){
Reportwtf ("Starting devicestoragemonitor Service", e );
}
The DSMs constructor code is as follows: DSMs constructor:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
  /**
* Constructor to run service. initializes the disk
Space
Threshold Value
* And posts an empty message to kickstart the process.
*/
Public devicestoragemonitorservice (context ){
Mlastreportedfreememtime = 0;
Mcontext = context;
Mcontentresolver = mcontext. getcontentresolver ();
// Create statfs object
Mdatafilestats = new statfs (data_path); // obtain data partition information;
Msystemfilestats = new statfs (system_path); // obtain the system partition information;
Mcachefilestats = new statfs (cache_path); // obtain the cache partition information;
// Initialize totalStorageOn Device
// Initialize the total device space information
// Mtotalmemory is used to save the total Data Partition space;
Mtotalmemory = (long) mdatafilestats. getblockcount ()*
Mdatafilestats. getblocksize ()/100l;
/*
Create three intents to notify users of insufficient storage space (action_device _Storage_ Low ),
The bucket returns to normal (action_device _Storage_ OK) and full storage space (action_device _Storage_ Full ).
Because the flag_receiver_registered_only_before_boot flag is set for each intent
Can be received by registered broadcastreceiver.
*/
Mstoragelowintent = new intent (intent. action_device _Storage_ Low );
Mstoragelowintent. addflags (intent. flag_receiver_registered_only_before_boot );
Mstorageokintent = new intent (intent. action_device _Storage_ OK );
Mstorageokintent. addflags (intent. flag_receiver_registered_only_before_boot );
Mstoragefullintent = new intent (intent. action_device _Storage_ Full );
Mstoragefullintent. addflags (intent. flag_receiver_registered_only_before_boot );
Mstoragenotfullintent = new intent (intent. action_device _Storage_ Not_full );
Mstoragenotfullintent. addflags (intent. flag_receiver_registered_only_before_boot );
// CacheStorageThresholds
/*
Query the Sys _Storage_ Threshod_percentage value. The default value is 10, that is, when data_path
When the remaining space in the directory is less than 10% of the total space, it is considered that the space is insufficient (action_device _Storage_ Low ).
*/
Mmemlowthreshold = getmemthreshold ();
/*
Query sys _Storage_ Full_threshold_bytes value. The default value is 1 MB, that is, when data_path
When the remaining space in the directory is less than or equal to 1 MB, The Task Space is full and the remaining space is reserved for the system.
*/
Mmemfullthreshold = getmemfullthreshold ();
/*
Check the storage space;
*/
Checkmemory (true );
}

Next, let's take a look at the implementation of the checkmemory () method.

Checkmemory () method:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
  Private final void checkmemory (Boolean checkcache ){
// If the thread that was started to clear cache is still
Running
Do nothing till its
// Finished clearing cache. Ideally this flag cocould be modified by using ache
// And shoshould be accessed via a lock but even if it does this test will fail now and
// Hopefully the next time this flag will be set to the correct value.
// If the thread is clearing the cache cache_path, no space check is performed.
If (mclearingcache ){
If (locallogv) slog. I (TAG, "thread already
Running
Just skip ");
// Make sure the thread is not hung for too long
Long difftime = system. currenttimemillis ()-mthreadstarttime;
If (difftime> (10*60*1000 )){
Slog. W (TAG, "thread that clears cache file seems to run for ever ");
}
} Else {
// Recalculate the remaining space of the three partitions;
Restatdatadir ();
If (locallogv) slog. V (TAG, "freememory =" + mfreemem); // post intent to icationicationmanager to display icon if necessary
//// If the remaining space is lower than mmemlowthreshold, the cache is cleared first;
If (mfreemem <mmemlowthreshold ){
If (! Mlowmemflag ){
If (checkcache ){
// See if clearing cache helps
// Note that clearing cache is asynchronous and so we do
// Memory check again once the cache has been cleared.
// First clear the cache
Mthreadstarttime = system. currenttimemillis ();
Mclearsucceeded = false;
Revoke AchE ();
} Else {
// If the space is still lower than mmemlowthreshold, send the broadcast and set
// Warning notification;
Slog. I (TAG,"RunningLow on memory. Sending notification ");
Sendnotification ();
Mlowmemflag = true;
}
} Else {
If (locallogv) slog. V (TAG,"RunningLow on memory "+
"Notification already sent. Do nothing ");
}
} Else {
If (mlowmemflag ){
// If the remaining space is no less than mmemlowthreshold and mlowmemflag has been set
// Cancel broadcasting with insufficient space.
Slog. I (TAG, "memory available. cancelling notification ");
Cancelnotification ();
Mlowmemflag = false;
}
}
If (mfreemem <mmemfullthreshold ){
// If the space is full, a broadcast with full space is sent;
If (! Mmemfullflag ){
Sendfullnotification ();
Mmemfullflag = true;
}
} Else {
If (mmemfullflag ){
// Cancel the broadcast if the broadcast space is not enough and the broadcast space is full.
Cancelfullnotification ();
Mmemfullflag = false;
}
}
}
If (locallogv) slog. I (TAG, "posting message again ");
// Keep posting messages to itself periodically
// Default_check_interval is 1 minute, that is, a check is triggered every 1 minute.
Postcheckmemorymsg (true, default_check_interval );
}
// Mlowmemflag and mmemfullflag indicate whether the broadcast ID is sent.

When the space is insufficient, DSMs first tries the sort ache function, which interacts with packagemanager-Service (PKMS). The Code is as follows:

[--> Devicestoragemanagerservice. Java: devicestoragemanagerservice]
Private final void upload AchE (){
If (mclearcacheobserver = NULL ){
// Create a cachepackagedataobserver object. When the PKMs clears the space, it calls back

// Onremovecompleted Function
Mclearcacheobserver = new cachepackagedataobserver ();
}
Mclearingcache = true; // set the value of mclearingcache to true, indicating that space is being cleared.

Try {
// Call the freestorageandnotify function of PKMs to clear the space. This function is introduced when analyzing PKMs.
Ipackagemanager. stub. asinterface (
Servicemanager. getservice ("package ")).
Freestorageandnotify (mmemlowthreshold, mclearcacheobserver );
// This function is available in packagemanagerservice. Java
}......
}
Cachepackagedataobserver is an internal class defined by DSMs. Its onremovecompleted function is very simple, that is, to resend the message device_memory_what (postcheckmemorymsg (false, 0);), so that DSMs can detect the storage space again. If the remaining space is less than 10%, a message indicating storage space running out is sent for sendnotification.
Devicestoragemanagerservice has a single function and does not overload the dump function. The only useful feature of diskstats-service is the dump function. I wonder why Google engineers didn't integrate the functions of devicestorage-managerservice and diskstatsservice.

PS:
If you are hungry and want to eat, I will ask your mom, "Are you ready? "This is a normal function call.

But today, it takes a long time for your mom to make dumplings. It's annoying to run and run. so you told your mom that I went out for a meeting and called my cell phone when I had dinner. after waiting for a while, your mom called you and said, "Open dinner. Come back for dinner! "

Here, you tell your mom to call you, that is, you save the callback function handle to your mom's action. Your mom calls you, that is, a callback process.
Summary:
(1) first obtain the data, system, and cache partition information in the constructor, and then register four intents, which are low memory, memory OK, and memory full, memory is not full in four cases. Obtain the percentage of the remaining space in the data directory of the settings database less than the total space, and obtain the critical value of the remaining space in the data directory of the database (used to prompt that the user space is full ). Then check the bucket; checkmemory (true );
(2)
When checking the bucket, first judge that if the thread is clearing the cache cache_path, no space check is performed. Otherwise, the remaining space of the three partitions is recalculated. If the remaining space is less than 10% in percentage, cache cleanup is performed first. After cleaning, a new round of checkmemory will be performed again, if the remaining space is less than the percentage of 10%, it is not used for cache cleaning and no notification is sent, the user is notified that the internal space exceeds the minimum value of 10%. If the space percentage is normal, but a notification has been sent, the notification is canceled. Similarly, if the space is full and exceeds the critical value of full, the broadcast with full space is sent; if the space is not full and the broadcast with full space has been sent, the broadcast is canceled. The checkmemory check is triggered every minute.
As follows: after cleaning, a new round of checkmemory will be performed again:
Perform the onremovecompleted action, which sends the message to check space [postcheckmemorymsg (false, 0); here, false means no longer executing mongoache], and then handle processes the message device_memory_what, enter checkmemory (false) Again, and send a notification to inform the user of the storage space running out. This prompt is displayed when there is no space of 10%.

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.