Link address
Tag Archives: Android
Linux learning experience sharing
1. What’s the use of learning Linux?
Learning Linux well will let you break the limitation of windows, come and go freely in the open source world, there are a lot of free software for you to use, especially the students of computer department,.
If you only use Linux as the only tool to make a living, you can choose the direction mainly in the operation and maintenance, system level software development and other fields. Linux occupies the vast majority of the server market, such as the Internet industry, front-end web development, back-end web servers, databases, storage devices are basically running on Linux, so you have to fight with Linux to do software development Although I think Linux brings you a different world view. There is no good or bad technology, the key is to see how you understand it.
2. I think there are many English words in Linux. Is it difficult to learn them?
Many people may think that there are many English words and documents in Linux. Is it difficult for us to learn them, but these commands are just abbreviations of English words, such as LS – list, CD – change directory, PWD – print working directory, CP – copy, MV – move, RM – remove these commands are abbreviations of English words, as long as you understand the meaning (understand), this shoe command will be very simple.
Therefore, don’t be afraid of English. English, as the most widely circulated language in the world, always has its value. It is also necessary to study and further study. Why not learn English together while learning Linux?If you have such an idea, then I’m sure you can learn Linux well.
3. I want to learn Linux, but I’m too busy with my work. I can learn less every day, and then Bala
Linux is a skill that makes a lot of things. In fact, it doesn’t require you to spend a lot of time learning it, but requires you to keep on and accumulate it. So, for office workers, it is the key to be good at using fragmented time. As long as you take out half an hour every day and persist in learning for a year, there will be a breakthrough!
Finally, there is the saying: “if you want to learn, nothing is an excuse. If you don’t want to learn, everything is an excuse.”
4. Some people say that “learning Linux is going in laughing and coming out crying”. Is that right?
Those who say that everything (skills) is easy to get started and difficult to learn later are all excuses for not learning well. Linux is just a basic computer skill. It has no requirements for learners’ background, knowledge structure and age. As long as they make unremitting progress, there is nothing they can’t learn. Of course, in learning there will always be bottlenecks, this time we need to self-regulation, adhere to. There are a lot of things to remember in learning Linux. If you are too lazy to recite, study and understand the command options of Linux, you will find it difficult to learn. Or that sentence, down-to-earth, there will always be harvest.
5. My qualifications are average and I don’t have any foundation. Generally, I have to study Linux in non working hours. How long can I pass RHCE?
It varies from person to person how long they have passed the certification. According to past experience, most people spend 1 or 2 hours a day studying hard for 2 to 4 months, so they should be able to pass the RHCE. I personally don’t agree with the method of storming RHCE half a month, because the certificate is secondary to learning Linux, and the main thing is to improve my working ability. Certification like this can be used as a phased goal for you to learn Linux, but it is not the main purpose of your study.
6. I want to teach myself Linux. What’s a good textbook to recommend.
When it comes to teaching materials, there are quite a lot of Linux teaching materials on the market. If you really want to recommend them, you can recommend many books. Next, I mainly recommend a book that I think is more suitable for beginners: This is how to learn Linux written by Liu Trent.
This book was started in 2015, and is still in the process of being written. It is a relatively new book. Compared with the Linux books on the market a few years ago, it is more suitable for the current environment, so as to improve the efficiency Redhat7 is a teaching system. Compared with other books, you can learn a lot of useful things. For a classmate with zero basis in Linux, the knowledge of this book is certainly enough, and what you have learned can be used in work It’s OK in the RHCE exam. The main points and difficulties of Linux system management are all covered in it. It’s easy to learn in order, and you don’t have to worry about the fracture of the knowledge layer.
7. I want to learn Linux, but I have no patience. How can I persist?
I don’t think this is a case. Many beginners will ask this question. In fact, what I want to say is that patience should be cultivated slowly. One of the most important things in learning Linux is interest. Generally speaking, people who want to learn Linux are interested in Linux or have what they want. In addition, a good learning environment and a good example will naturally lead to patience If you keep learning, you will be in touch with Linux every day. You can turn books whenever you have time. Therefore, interest is the best teacher. Although this sentence is vulgar, it’s quite right.
8. I want to learn Linux. Can I completely study by myself without taking any training courses?
You can download a free copy of “this is how to learn Linux” http://www.linuxprobe.com/book Take a look at it by self-study, but I don’t recommend not to apply for classes at all. In fact, Linux is a simple thing: you will use it after you learn it. For example, when you take exams and use them in your work, you will be short of learning by yourself at the beginning, which will directly affect your study time and greatly increase the cost of study. Therefore, when you first get started, you still need a Linux teacher to guide you to get started;
when you get started, you need a Linux teacher to help you get started Secondly, in fact, there are certain rules in learning Linux. We can call it the knowledge architecture of Linux. If you just look at the content in the textbook without the teacher’s summary and explanation, it’s easy to forget after learning. If you follow the teacher to learn Linux at the beginning, you can establish the correct knowledge architecture of Linux. On the contrary, if you don’t set up a good structure at the beginning, even if you teach yourself to the intermediate level, you may find it difficult to learn in the face of some unfamiliar problems, and your interest in learning will weaken, leading to giving up in the end. In addition, if it’s class learning, you can find like-minded partners to study together in a class, which is also a kind of promotion for your own learning.
Generally speaking, they can learn by themselves, but they are difficult and easy to take detours. Knowledge on the Internet is scattered, and there are mistakes and loopholes. If there is a teacher’s advice, on the one hand, it can help you to summarize in time, on the other hand, it can also play a role in urging you to learn.
Several properties of Android listview
First is the stackFromBottom property, after this property your finished list will be displayed at the bottom of your list, with the values true and false
android:stackFromBottom="true"
The second is the transciptMode property, you need to track or view information in real time with a ListView or other control that displays a large number of Items, and you want the newest items to be automatically scrolled to the visible range. The control transcriptMode property can be set to automatically scroll to the bottom of the Android platform control (which supports ScrollBar) by setting
android:transcriptMode="alwaysScroll"
The third cacheColorHint property is that many people want to change the background to match the overall UI design, it's easy to change the background by preparing an image and specifying the property android:background="@drawable/bg", but don't be too happy, after you do that, you will find that the background is but when you drag or click on the blank position of the list, you will find that the ListItem becomes black, which ruins the overall effect.
If you just change the color of the background, you can directly specify android:cacheColorHint as the color you want, if you are using pictures as the background, then also just specify android:cacheColorHint as transparent (#00000000) on it!
The fourth divider attribute, the role of this attribute is to set a picture as a spacer between each item, or to remove the divider line between the items
android:divider="@drawable/list_driver" where @drawable/list_driver is an image resource, if you don't want to show the divider, just set it to android:divider="@drawable/@null" and you're done.
The fifth fadingEdge property, with black shadows on the top and bottom edges
android:fadingEdge="none" set to no shadow~
The fifth scrollbars property, which hides the scrollbars of the listView, is
android:scrollbars="none" and setVerticalScrollBarEnabled(true); the effect is the same, hidden when inactive and hidden when active
The sixth fadeScrollbars property, android:fadeScrollbars="true", can be set to true when configuring the ListView layout to achieve automatic hiding and displaying of scrollbars.
The precision of decimal calculation with double and float in Java is not accurate
The precision of decimal calculation with double and float in Java is not accurate
In most cases, using double and float to calculate the result is accurate, but in some systems with high accuracy requirements or known decimal calculation results will not be accurate, this problem is very serious.
《Effective Java “refers to a principle, that is, float and double can only be used for scientific calculation or engineering calculation, but we should use them in commercial calculation java.math.BigDecimal By using the BigDecimal class, we can solve the above problems. The designer of Java provides a very useful class BigDecimal for programmers, which can improve the problem that the float and double classes can’t calculate accurately I’m sorry.
The example code is as follows:
package ex;
import java.math.*;
public class BigDecimalDemo {
public static void main(String[] args){
System.out.println(ArithUtil.add(0.01, 0.05));
System.out.println(ArithUtil.sub(1.0, 0.42));
System.out.println(ArithUtil.mul(4.015, 100));
System.out.println(ArithUtil.div(123.3, 100));
}
}
class ArithUtil{
private static final int DEF_DIV_SCALE=10;
private ArithUtil(){}
//+
public static double add(double d1,double d2){
BigDecimal b1=new BigDecimal(Double.toString(d1));
BigDecimal b2=new BigDecimal(Double.toString(d2));
return b1.add(b2).doubleValue();
}
//-
public static double sub(double d1,double d2){
BigDecimal b1=new BigDecimal(Double.toString(d1));
BigDecimal b2=new BigDecimal(Double.toString(d2));
return b1.subtract(b2).doubleValue();
}
//*
public static double mul(double d1,double d2){
BigDecimal b1=new BigDecimal(Double.toString(d1));
BigDecimal b2=new BigDecimal(Double.toString(d2));
return b1.multiply(b2).doubleValue();
}
// /
public static double div(double d1,double d2){
return div(d1,d2,DEF_DIV_SCALE);
}
public static double div(double d1,double d2,int scale){
if(scale<0){
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b1=new BigDecimal(Double.toString(d1));
BigDecimal b2=new BigDecimal(Double.toString(d2));
return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}
}
Now let’s analyze in detail why floating-point operations cause precision loss?
1. Binary representation of decimals
First we need to clarify the following two issues.
(1) How to convert decimal integers to binary numbers
The algorithm is simple. As an example, 11 is expressed as a binary number.
11/2=5 remainder 1
5/2=2 remainder 1
2/2=1 remainder 0
1/2=0 remainder 1
End of 0 11 is represented in binary as (from bottom to top):1011
In other words, will the algorithm for converting all integers into binary numbers go on indefinitely? Absolutely not, integers can always be represented exactly in binary, but not decimals.
(2) How decimal decimals are converted into binary numbers
The algorithm is to multiply by 2 until there are no more decimals. As an example, 0.9 is expressed as a binary number
0.9*2=1.8 Take the integer part 1
0.8(fractional part of 1.8)*2=1.6 Take the integer part 1
0.6*2=1.2 Take the integer part 1
0.2*2=0.4 Take the integer part 0
0.4*2=0.8 Take integer part 0
0.8*2=1.6 Take integer part 1
0.6*2=1.2 Take integer part 0
......... 0.9 Binary representation (from top to bottom): 1100100100100 ......
Note: The above calculation process is circular, which means that *2 can never eliminate the fractional part, so that the algorithm will go on indefinitely. Obviously, the binary representation of decimals is sometimes impossible to be exact. The reason is simple: can 1/3 be represented accurately in the decimal system? This explains the loss of precision in floating-point subtraction, where "subtraction is incomplete".
.
2. Storage of float type in memory
It is well known that Java's float type takes up 4 bytes in memory. float's 32 binary bits are structured as follows
float memory storage structure
4bytes 31 30 29 ----23 22 ----0
Indicates real sign bit Exponential sign bit Exponential bit Valid number of bits
Where the sign bit 1 means positive and 0 means negative. The valid bits are 24 bits, one of which is the real sign bit.
The steps to convert a float type to memory storage format are
(1) First convert the absolute value of this real number into binary format, noting that the binary methods for the integer and decimal parts of the real number have been discussed above.
(2) Shift the decimal point of this binary format real number left or right by n bits until the decimal point moves to the right of the first significant digit.
(3) Count out twenty-three digits from the first digit to the right of the decimal point into the 22nd to the 0th digit.
(4) If the real number is positive, put a "0" in the 31st place, otherwise put a "1".
(5) If n is shifted to the left, the exponent is positive and "1" is placed in the 30th place. If n is shifted to the right or n=0, then "0" is placed in the 30th position.
(6) If n is obtained by left shift, n is converted to binary by subtracting 1 and adding "0" to the left to make up the seven bits and put it into the 29th to 23rd place. If n is shifted to the right or n=0, then n is converted to binary and "0" is added to the left to make up the seven bits, and then each bit is inverted and placed in bits 29 to 23.
Example: Memory storage format of 11.9
(1) The memory storage format of 11.9 is approximately "1011. 11100110011001100110011001100..." after converting 11.9 to binary. .".
(2) Shift the decimal point three places left to the right of the first significant digit: "1. 011 11100110011001100110". Ensure that the number of significant digits is 24, with the extra intercept on the right (where the error is created ).
(3) This already has twenty-four valid digits, remove the leftmost "1" to get "011 11100110011001100110" with 23 bits. (4) Since 11.9 is a valid number, it is a valid number.
(4) Since 11.9 is a positive number, put "0" in the 31st real sign bit.
(5) Since we are shifting the decimal point to the left, we put "1" in the 30th exponent sign position.
(6) Since we are shifting the decimal point 3 places to the left, we subtract 1 from 3 to get 2, convert it to binary, and add 7 bits to get 0000010, and put it in the 29th to 23rd place.
The final representation of 11.9 is: 0 1 0000010 011 11100110011001100110
Another example: the memory storage format of 0.2356
(1) After converting 0.2356 to binary, it is approximately 0.00111100010100000100100000.
(2) Move the decimal point three places to the right to get 1.11100010100000100100000.
(3) Count out twenty-three valid digits from the right of the decimal point, i.e. 1110001010100000100100000.
into the 22nd to the 0th digit.
(4) Since 0.2356 is positive, put a "0" in the 31st place.
(5) Since we have shifted the decimal point to the right, we put a "0" in the 30th place.
(6) Because the decimal point is shifted to the right by 3 bits, so the 3 is converted to binary, and the "0" is added to the left to make up the full seven
(6) Because the decimal point is shifted to the right by 3 bits, the 3 is converted to binary, and the "0" is added to the left to make up the seven bits to get 0000011.
The final value of 0.2356 is: 0 0 1111100 11100010100000100100000
Steps to convert a memory-stored float binary format to decimal.
(1) Write out the binary number from the 22nd to the 0th digit, and add a "1" to the leftmost digit to get twenty-four valid digits. Put the decimal point to the right of the leftmost "1".
(2) Take out the value n from the 29th to the 23rd digit, and invert the n digit when the 30th digit is "0". When the 30th digit is "1", increment n by 1.
(3) Shift the decimal point left by n (when the 30th digit is "0") or right by n (when the 30th digit is "1") to obtain a real number in binary.
(4) Convert this binary real number to decimal and add a plus or minus sign depending on whether the 31st bit is a "0" or a "1".
3. Subtraction of floating point
The process of adding and subtracting floating point is more complex than the process of fixed point. The process of completing a floating point addition or subtraction operation is roughly divided into four steps.
(1) Checking of the 0 operand.
If one of the two floating-point numbers to be added or subtracted is 0, the result of the operation is known without the need to perform some sequential operations.
(2) Comparing the magnitude of the ordinal (exponent bits) and completing the pair order.
To add or subtract two floating-point numbers, we must first see whether the exponent bits of the two numbers are the same, i.e., whether the decimal point positions are aligned. If the two numbers have the same exponent, it means the decimal points are aligned, and the addition and subtraction of the last number can be performed. On the contrary, if the two numbers have different ordinates, it means that the decimal points are not aligned, so we must make the ordinates of the two numbers the same, and this process is called pairing.
How to pair order (assuming two floating point numbers with exponent bits Ex and Ey ).
By shifting the mantissa to change Ex or Ey so that they are equal. Since floating point numbers are mostly speciated, shifting the trailing left number will cause the loss of the highest significant bit, resulting in a large error; while shifting the trailing right number will cause the loss of the lowest significant bit, but the error caused is smaller, therefore, the pairwise order operation requires that the trailing right number be shifted, and after the trailing right number is shifted, the order code is increased accordingly, while its value remains unchanged. Obviously, if one of the increased ordinals is equal to the other, the increased ordinal must be a small one. Therefore, in the order pairing, always make the small order to the large order, that is, the end of the small order shift to the right (equivalent to the decimal point left shift), each right shift one, its order code plus 1, until the two numbers of the order code equal, the number of right shift is equal to the order difference △ E.
(3) The mantissa (valid digits) is added or subtracted.
(4) The result is normalized and rounded.
Android realizes the fade in and fade out of animation effect
View fade animation effect
/**
* View fade animation effect
*/
public void setHideAnimation( View view, int duration)
{
if (null == view || duration < 0)
{
return;
}
if (null != mHideAnimation)
{
mHideAnimation.cancel();
}
// Listening for the end of animation operations
mHideAnimation = new AlphaAnimation(1.0f, 0.0f);
mHideAnimation.setDuration(duration);
mHideAnimation.setFillAfter(true);
view.startAnimation(mHideAnimation);
}
View fade animation effect
/**
* View fade animation effect
*/
public void setShowAnimation( View view, int duration)
{
if (null == view || duration < 0)
{
return;
}
if (null != mShowAnimation)
{
mShowAnimation.cancel();
}
mShowAnimation = new AlphaAnimation(0.0f, 1.0f);
mShowAnimation.setDuration(duration);
mShowAnimation.setFillAfter(true);
view.startAnimation(mShowAnimation);
}
It is best to monitor the beginning and end of the animation. For showview, call showView.setVisibility ( View.VISIBLE )Set to visible before calling showView.animate ()
for hideview, call hideView.animate (), and finally invoked in the onAnimationEnd event. hideView.setVisibility ( View.GONE ); set to invisible
Monitor processing: View fade animation effect
/**
* View fade animation effect
*/
public void setHideAnimation( final View view, int duration)
{
if (null == view || duration < 0)
{
return;
}
if (null != mHideAnimation)
{
mHideAnimation.cancel();
}
// Listening for the end of animation operations
mHideAnimation = new AlphaAnimation(1.0f, 0.0f);
mHideAnimation.setDuration(duration);
mHideAnimation.setFillAfter(true);
mHideAnimation.setAnimationListener(new AnimationListener()
{
@Override
public void onAnimationStart(Animation arg0)
{
}
@Override
public void onAnimationRepeat(Animation arg0)
{
}
@Override
public void onAnimationEnd(Animation arg0)
{
view.setVisibility(View.GONE);
}
});
view.startAnimation(mHideAnimation);
}
Monitor processing: View fade animation effect
/**
* View fade animation effect
*/
public void setShowAnimation( final View view, int duration)
{
if (null == view || duration < 0)
{
return;
}
if (null != mShowAnimation)
{
mShowAnimation.cancel();
}
mShowAnimation = new AlphaAnimation(0.0f, 1.0f);
mShowAnimation.setDuration(duration);
mShowAnimation.setFillAfter(true);
mShowAnimation.setAnimationListener(new AnimationListener()
{
@Override
public void onAnimationStart(Animation arg0)
{
view.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationRepeat(Animation arg0)
{
}
@Override
public void onAnimationEnd(Animation arg0)
{
}
});
view.startAnimation(mShowAnimation);
}
Note: I found that after setting the view control fade, and gone (completely invisible), after these two properties. When you click the position of the control, the click event of the view will still start. However, when view gone is set separately, if you click view, there will be no response. It’s hard for me to understand. Just in the project, the click of this view needs to be processed, so when I set gone to view, I will set clickable to false again.
Android Cannot merge new index 67208 into a non-jumbo instruction
The solution given online is to add dex.force.jumbo=true to the project.properties file, then clean up the project and recompile it.
Bitmap optimization and memory optimization
Is it necessary for bitmap to call recycle method in Android system
Before Android 3.0, bitmap image data was processed in the underlying C, so before Android 3.0, recycle() should be called. Although finalize() will call recycle(), students who are experienced in Java should know that there are many problems in releasing resources only by finalize()
After Android 3.0, the image data is put in a member variable mbuffer [] of the bitmap object. Therefore, it is not necessary to call recycle (). After the bitmap is set to null, the image data will be recycled by GC.
Now that Android is in the age of 5.0, it is recommended not to consider supporting versions before 3.0.
actually Bitmap.recycle This is an advanced call, and normally need not be called, since the normal GC process will free up this memory when there are no more references to this bitmap. When no reference points to a bitmap, GC will automatically free memory.)
Managing bitmap memory Google’s official explanation of bitmap
In addition to the steps described in Caching Bitmaps, there are specific things you can do to facilitate garbage collection and bitmap reuse. The recommended strategy depends on which version(s) of Android you are targeting. The BitmapFun sample app included with this class shows you how to design your app to work efficiently across different versions of Android.
To set the stage for this lesson, here is how Android’s management of bitmap memory has evolved:
On Android Android 2.2 (API level 8) and lower, when garbage collection occurs, your app’s threads get stopped. This causes a lag that can degrade performance. Android 2.3 adds concurrent garbage collection, which means that the memory is reclaimed soon after a bitmap is no longer referenced.
On Android 2.3.3 (API level 10) and lower, the backing pixel data for a bitmap is stored in native memory. It is separate from the bitmap itself, which is stored in the Dalvik heap. The pixel data in native memory is not released in a predictable manner, potentially causing an application to briefly exceed its memory limits and crash. As of Android 3.0 (API level 11), the pixel data is stored on the Dalvik heap along with the associated bitmap.
The following sections describe how to optimize bitmap memory management for different Android versions.
Memory optimization
Memory optimization from: http://my.oschina.net/u/1753339/blog/223379
It’s easy to load a picture on the UI of your application, but when you need to load a lot of pictures on the UI, the situation becomes more complicated. In many cases (such as using listview, GridView or viewpager), the images displayed on the screen can be increased continuously by sliding the screen and other events, which eventually leads to oom.
In order to ensure that the use of memory is always maintained in a reasonable range, the removed screen images are usually recycled. At this time, the garbage collector will also think that you no longer hold the reference of these images, so it will GC these images. It’s very good to use this idea to solve the problem, but in order to make the program run quickly and load pictures on the interface quickly, you have to consider the situation that the user slides some pictures back into the screen after they are recycled. At this time, reloading the image just loaded is undoubtedly the bottleneck of performance. You need to find a way to avoid this situation.
At this time, the use of memory caching technology can solve this problem, it can let components quickly reload and process images. Now let’s take a look at how to use memory caching technology to cache images, so that your application can improve the response speed and fluency when loading many images.
Memory caching technology provides a fast way to access images that occupy a lot of valuable memory of applications. The core class is lrucache (this class is provided in the package of android-support-v4). This class is very suitable for caching images. Its main algorithm principle is to store the most recently used objects in LinkedHashMap with strong references, and remove the least recently used objects from memory before the cache value reaches the preset value.
In the past, we often used a very popular implementation of memory caching technology, namely soft reference or weak reference. However, this method is no longer recommended, because since Android 2.3 (API level 9), the garbage collector tends to recycle objects with soft references or weak references, which makes soft references and weak references unreliable. In addition, in Android 3.0 (API level 11), the image data will be stored in the local memory, so it can not be released in a predictable way, which has the potential risk of causing the memory overflow and crash of the application.
In order to select an appropriate cache size for lrucache, the following factors should be considered, for example:
How much memory can your device allocate for each application?
How many pictures can be displayed on the device screen at a time?How many images need to be preloaded because they may be displayed on the screen soon?
What is the screen size and resolution of your device?A super-high resolution device (such as Galaxy nexus) needs more cache space than a lower resolution device (such as nexus s) when holding the same number of images.
The size and size of the image, and how much memory space each image will occupy.
How often are images visited?Will some pictures be visited more frequently than others?If so, you may want to keep some images resident in memory, or use multiple lrucache objects to distinguish different groups of images.
Can you keep the balance between quantity and quality?Sometimes, it’s more effective to store multiple low pixel images, but it’s more effective to load high pixel images in the background.
There is no specified cache size for all applications, which is up to you. You should analyze the memory usage of the program, and then work out an appropriate solution. A too small cache space may cause images to be released and reloaded frequently, which is not good. However, if the cache space is too large, it may still cause problems java.lang.OutOfMemory It’s abnormal.
Here is an example of using lrucache to cache images:
private LruCache<String, Bitmap> mMemoryCache;
@Override
protected void onCreate(Bundle savedInstanceState) {
// Get the maximum value of available memory, using memory beyond this value will raise an OutOfMemory exception.
// LruCache passes in the cache value in KB through the constructor.
int maxMemory = (int) (Runtime.getRuntime().maxMemory() /1024);
// Use 1/8 of the maximum available memory value as the size of the cache.
int cacheSize = maxMemory/8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// Override this method to measure the size of each image and return the number of images by default.
return bitmap.getByteCount()/1024;
}
};
}
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
public Bitmap getBitmapFromMemCache(String key) {
return mMemoryCache.get(key);
}
In this example, one eighth of the memory allocated by the system to the application is used as the cache size. In medium and high configuration mobile phones, there will be about 4 megabytes (32g8) of cache space. If a full screen GridView is filled with four 800×480 resolution images, it will occupy about 1.5 megabytes of space (800 * 480 * 4). Therefore, this cache size can store 2.5 pages of images.
When a picture is loaded into ImageView, it will be checked in the cache of lrucache first. If the corresponding key value is found, the ImageView will be updated immediately. Otherwise, a background thread will be started to load the image.
public void loadBitmap(int resId, ImageView imageView) {
final String imageKey = String.valueOf(resId);
final Bitmap bitmap = getBitmapFromMemCache(imageKey);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
imageView.setImageResource(R.drawable.image_placeholder);
BitmapWorkerTask task = new BitmapWorkerTask(imageView);
task.execute(resId);
}
}
Bitmapworkertask also puts the key value pair of the newly loaded image into the cache.
class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
// loading the pictures
@Override
protected Bitmap doInBackground(Integer... params) {
final Bitmap bitmap = decodeSampledBitmapFromResource(
getResources(), params[0], 100, 100);
addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
return bitmap;
}
}
(how to define the key of image key value pair?Path to image (URI)
What are the common memory leaks in Android
Query database without closing cursor
In Android, Cursor is a very common object, but in writing code, people often forget to call close, or because of the code logic problem situation, close is not called.
Usually, in an activity, we can call startmanagingcursor or directly use managedquery to let the activity automatically manage the cursor object.
However, it should be noted that when activity is introduced, cursor will no longer be available!
If the code of operating cursor is not synchronized with UI (such as background thread), there is no need to judge whether the activity has ended or wait for the background thread to end before calling ondestroy.
In addition, the following is also a common case that the cursor will not be closed:
although it seems that, Cursor.close () has been called, but if there is an exception, close () will be skipped, resulting in a memory leak.
Therefore, our code should be written in the following way:
Cursor c = queryCursor();
try {
int a = c.getInt(1);
......
} catch (Exception e) {
} finally {
c.close(); //Call close() in finally, ensuring that it will be called
}
try {
Cursor c = queryCursor();
int a = c.getInt(1);
......
c.close();
} catch (Exception e) {
}
Unregisterreceiver() was not called after calling registerreceiver
After calling registerreceiver, if unregisterreceiver is not called, it will occupy a large amount of memory.
We can often see the following code:
this is a very serious error, because it will cause the broadcastreceiver not to be unregistered, resulting in memory leakage.
registerReceiver(new BroadcastReceiver() {
...
}, filter); ...
*InputStream/OutputStream not closed*
When using files or accessing network resources, using InputStream/OutputStream will also lead to memory leakage
Recycle () is not called after bitmap is used
according to the description of SDK, it is not necessary to call recycle. However, when we call recycle (), we no longer use memory as much as possible.
Context leak
this is a very obscure memory leak.
Let’s take a look at the following code:
in this code, we use a static drawable object.
This usually happens when we need to call a drawable frequently, and its loading is time-consuming. We don’t want to create the drawable every time we load an activity.
At this point, using static is undoubtedly the fastest way to write code, but it is also very bad.
When a drawable is attached to a view, the view will be set to the callback of the drawable Drawable.setCallback () Implementation).
This means that the drawable has a reference to textview, which in turn has a reference to activity.
As a result, the memory will not be released after the activity is destroyed.
19 Android must kill gadgets
19 Android must kill gadgets
1. Xappdbg
xappdbg is an application development tool that can change the parameters in the code during operation. This tool can save you a lot of time, because you don’t have to recompile and run your program for every small change of the application.
2. Chkbugreport
this tool can quickly check the output Android error reports. It does semantic analysis from a large number of text files output by Android error reporting tool, and then parses them into a more readable document, which is easier to analyze. Chkbugreport is also an open source project.
3. Apkanalyser
this is a static and virtual analysis tool. You can have a comprehensive overview of the application architecture. You can use it to check API references, check application dependencies, and decompile bytecode. Apkanalyser is a complete open source tool chain. It supports modifying the application binary code. You can repackage, install, run and verify the results of logcat.
4. Appxplore
with the appxplore tool, you can browse all the apps installed on your Android device, and analyze the details of many apps — app version, package name, certificate, permission, signature, activities and other information that can’t be viewed on many devices. Appxplore is especially useful for checking the memory size occupied by the application when it is running and whether the files can be moved to the SD card. Similarly, developers can test and ensure the quality of the application. This ensures that the application displays the appropriate permissions on the manifest file.
5. Memory analyzer (MAT)
memory analyzer on eclipse is a fast and functional Java heap analysis tool, which can help you find memory leaks and reduce memory overhead. Using memory analyzer, we can analyze millions of objects and multiple heap dumps, quickly count the number of objects left, so that we can see which objects prevent the garbage collector from collecting. Finally, run a report to automatically report the suspicious place that caused the leak.
6. Eclipse Plug-in sqlitemanger
this plug-in can help developers view and modify SQLite database on eclipse.
7. Robotium
robotium is a testing framework, which can simply write a powerful and robust automatic black box test container for Android applications. With robotium, test developers can support a variety of Android activities to write function, system and acceptance test scripts. Robotics fully supports activity, dialogues, toast, menus and context menus.
8. Acra
acra is a function library that allows Android applications to automatically issue Google doc format crash reports. Android developers can get the data of application crash or wrong behavior through acra. If a crash occurs, your application will not add user alerts beyond the existing system crash alerts or reporting functions. If toast, status bar or direct dialog mode is used, the “forced close” dialog will no longer be displayed. Even if the reminder function of the native system on the device is turned on, another report cannot be sent.
Br> the Android binder will convert all of your Android layout statements into a series of XML files. Type a prefix, select the range to paste on the XML file, and then click generate. Select “verb” to find out why all the areas are skipped.
10. The ever expanding ecosystem of Android devices has brought unique challenges to test applications. Spoon simplifies this task by assigning execution of instrumentation tests and displaying results in a more meaningful way. Instead of trying to be a new form of testing, spoon makes the current instrumentation testing more useful. With the application’s APK and instrumentation APK, spoon can run tests on multiple devices at the same time. Once all the tests are completed, a static HTML summary is generated that includes the details of the various device tests.
11. Android content provider code generator
do you often copy and paste a lot of code to write a content provider?Then this code generation tool can help you.
12. Start your next android app in 10 seconds. Android KickStarter uses the most popular library to help you quickly build a configured android app. It creates and configures projects for you, and focuses directly on the code!
13. Android holo color generator
this Android holo color generator allows you to simply create Android components for your application, such as editext or spinner, and use your own colors. It will generate all nine necessary patch assets and related XML drawables and styles files, which can be directly copied into your project.
14. Actionbar style generator
this actionbar style generator allows you to easily create a concise, attractive and bug free custom actionbar. It will generate all nine necessary patch assets and related XML drawables and styles files, which can be copied directly into your project.
15. Asset studio
asset Studio allows you to quickly and easily generate icons from existing images, clip art or text resources.
16. Little eye labs
little eye labs is a performance analysis tool for Android applications. Its product has been renamed “little eye” instead of “little eye appinsight”. Keep our product catalog concise, consistent with the overall theme that we focus on simplicity in each part of our work.
Main features:
outline any application;
record and playback video;
front end and background usage;
consumption of CPU, memory and data;
manual or automatic heap dump;
save and share.
17. The concept of “overdraw” is considered to be very important in the Android world. At the Google I/O conference, few speeches emphasized the importance of reducing overdraft. This is the first tool (the best I know) that can help us easily identify overdrafts.
Main features
3D query;
find overdraft;
box model;
combine with DDMS;
view hierarchy;
background/content;
webgl;
2D to 3D to 2D;
· more
18. Android Button Maker
Android Button Maker is a tool that can generate button code online. The Android API provides drawable resources for geometric shapes defined by XML files, including colors, boundaries, and gradients. The generation of these buttons is based on XML code in drawable form, which can load faster than ordinary PNG buttons. You can customize the properties of the button on the settings panel and get its source code.
19. Jsonschema2pojo
is used to generate POJO (plain old Java object) class on JSON architecture. This small and powerful tool can save you the time to write POJO.
Android gets the height and width of the screen
Android gets the height and width of the screen and uses the WindowManager class
There are two methods
1、WindowManager wm = (WindowManager) getContext()
.getSystemService(Context.WINDOW_SERVICE);
int width = wm.getDefaultDisplay().getWidth();
int height = wm.getDefaultDisplay().getHeight();
2、WindowManager wm = this.getWindowManager();
int width = wm.getDefaultDisplay().getWidth();
int height = wm.getDefaultDisplay().getHeight();
Android EditText cursor control, color modification, show and hide
Modify the Android EditText cursor color:
QQ group: 372135639
EditText has one property: android:textCursorDrawable This property is used to control the color of the cursor
android:textCursorDrawable= ”@The function of “null” and “@ null” is to make the cursor color the same as text color
Android set EditText cursor color and thickness:
In the Android input box, if you want to change the color and thickness of the cursor, you can do it in the following two steps:
1. Create a new cursor control color in the resource file drawable_ cursor.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<size android:width="1dp" />
<solid android:color="#008000" />
</shape>
Set the EditText cursor to show/hide
android:cursorVisible= ”True “//displays
the android:cursorVisible= ”False “//hide
Note: default display
//The cursor displays the problem by default. It will not be displayed by default on Meizu mx6. (it is better to control the display and hiding of cursor by code)
Android get screen width and height and get control width and height
The width and height of a control have a drawing process. The width and height of the control are directly obtained in the oncreate method, which is generally 0. Therefore, we need to use the following methods to obtain the width and height of the control:
Load onmeasure twice, but the callback function only calls back once
ViewTreeObserver vto2 = imageView.getViewTreeObserver();
vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
imageView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
textView.append("\n\n"+imageView.getHeight()+","+imageView.getWidth());
}
});
ADT:v22.6.2-1085508 Creating Android project and creating appcompat automatically_ V7 solution
When setting up an Android application, you only need to select the minimum required SDK to Android 4.0 (API 14) or above, and there will be no annoying appcompat_ V7