Android Source problem solution (Exception handling)

Source: Internet
Author: User

CASE1: How do I press the back key to continue running without exiting the app background?

In the base class activity will call onbackpressed This method, this method will finish the current activity, so that the current activity to go to ondestory, if you want to press the back key does not go to ondestory, Requires a carbon onbackpressed method @Override
public void onbackpressed () {
TODO auto-generated Method Stub
Super.onbackpressed ();
Movetasktoback (TRUE);
}
Call Movetasktoback (true) to have the task execute in the background, as with the home key
Case2:How Android debugging gets the time difference
1, refer to the following namespace:
Import Java.util.Date;
Import Android.text.format.DateFormat;
2, set the time format:
SimpleDateFormat df = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
3, Get time:
Date curdate = new Date (System.currenttimemillis ());
Processing
Date endDate = new Date (System.currenttimemillis ());
Long diff = enddate.gettime ()-curdate.gettime ();
This is the time interval, and is the MS level, through the log can be printed out

CASE3:How does the ListView default to the last record where it was displayed instead of ending?

When a ListView displays many data in the system, or if a piece of data is too long, such as exceeding the height of the entire screen, the display automatically jumps to the end of the last data, which is controlled by the property Transcriptmode.

The value used for the property and the meaning is:

Disabled 0 disables transcript mode. This is the default value.

Normal 1 The list would automatically scroll to the bottom when a data set change notification are received and only if the Last item was already visible on screen.

Alwaysscroll 2 The list would automatically scroll to the bottom and no matter what items is currently visible.


But if we want to scroll and don't want it to jump to the beginning of the last record, we'll set it up in the code as follows:

Mlistview.setselection (Listviewadapter.getcount ())

In addition , the default value for the Transcriptmode property is disabled

Case4: repeated testing of the same problem in the browser sometimes "browser stopped running"? Like constantly adding bookmarks, constantly on-demand videos, etc.

1. Problem analysis

This problem typically prints the following trace in Main.log:

11-19 06:00:46.570 880 1870 E cursorwindow:could not allocate Cursorwindow '/data/data/com.android.browser/databases/b Rowser2.db ' of size 2097152 due to error-24


This represents the FD exceeded, the number of FD in Android limit is 1024, more than this number, will report the above exception.


You can also use the following command to further confirm whether the FD exceeded and which file handle exceeded:

ADB shell
PS | BusyBox grep com.android.browser Get PID
lsof | BusyBox grep pid

the BusyBox command must be guaranteed to be in the Userdebug version, not the user version

If the above command is found to be a large number of FD, and there is an increasing trend, generally more than 300 is considered abnormal, the maximum will not exceed 1024


2. Problem locating

The first is to troubleshoot the code you added there is no FD leak, such as Cusros did not close or close the exception, thread execution shutdown is not released, these are the most common FD exceeded.

Confirm your code is not a problem, suspicion is the problem of the platform, you can send the log and browser code to the Spreadtrum to analyze.

CAES5: How does a Common task delay work in Android?

1. The most common is the use of thread, generally:

New Thread (New Runnable () {
public void Run () {
Thread.Sleep (n);
Handler.sendmessage ();//Go tell the main thread to start working.
}
}). Start

2. Using handler to achieve

New Handler (). postdelayed (New Runnable () {
public void Run () {
Do what you want to do.
}
}, delay);

3. Use a timer to achieve

Timer = new timer (true);
TimerTask = new TimerTask () {
public void Run () {
Do what you want to do.
}
};
Timer.schedule (timertask, delay);

These three ways are often used by us.

4. Using timer Alarmmanager to achieve, we often use the calendar and alarm clock is the main use of the service; The main function is to broadcast a specified intent at a particular moment; it's simply that we set a time and then when that time comes, Alarmmanager for us to broadcast a intent that we set


Case6: How do you measure code performance?

Java and Android provide the following APIs that allow applications to measure time and performance:

System.currenttimemillis

System.nanotime

Debug.threadcputimenanos

Systemclock.currentthreadtimemills

Systemclock.elapsedrealtime

Systemclock.uptimemillis

The above functions, even if some methods return time in nanoseconds, do not mean that the accuracy is nanosecond. The actual accuracy depends on the platform. Millisecond precision for the same reason.

Typical code for test time:

Long startTime = System.nanotime ();

Code to be tested

Long Duration = System.nanotime ()-startTime;

This code is fully referenced by the Java class, so it can be used on platforms other than Android. The Debug and Systemclock classes are unique to Android.

Although System.currenttimemillis () can be used as a means of measuring time, this method is not recommended for the following reasons:

1) Its accuracy and accuracy is not enough

2) Changing the system time will affect its results

It is recommended to use System.nanotime () because it provides better accuracy and accuracy. System.nanotime () has no reference time defined and can only be used to measure time intervals. The System.currenttimemilis () return value is the number of milliseconds between 00:00:00 UTC and the current time of January 1, 1970.

The execution time of the system.nanotime () itself is at the order of 750 nanoseconds.

Note that the operation of the measurement may be interrupted several times because of multithreading, to give up CPU time to other threads. Therefore, the measurement results may include some time to execute other code, which may lead to incorrect time measurement results and misleading. You can use the Android Debug.threadcputimenano () method to measure the execution time of your code, which is better. Because Debug.threadcputimenanos () only measures the time spent in the current thread, its results are more accurate. However, if the part to be measured runs on multiple threads, calling only once Debug.threadcputimenanos () does not give an accurate estimate, it must be called on all involved threads and the results added.

Case7: How to check if the SIM card is out of the card and how to deal with the lost card
can be analyzed by analyzing Android radio log in "At+cpin?" command to confirm the current status of the SIM card.

04:03:56.470 164 855 D Use-rlog/rlog-at: [w] channel1:at> At+cpin?
04:03:56.470 164 D Use-rlog/rlog-at: [w] channel1:at< +cme error:10

Normally, a +cpin:xxxx is returned or returned directly to OK.
When the +CME error is returned and error cause is ' 10 ', that means that the phone is a SIM card-drop phenomenon.

After the SIM card has been dropped, please give priority to the modem log for analysis if the software is abnormal,

In addition, hardware synchronization is required to confirm whether there is radio frequency interference and card slot loosening situation.

CAES8: How to locate the modem reset restart problem

When the modem resets, there will be abnormal communication functions such as NET/drop cards/dropped words,
How to locate the current modem reset, you can query the main log of Android is similar to the following key information (modem assert happen)
02-25 10:08:02.041 137 393 D modemd:buf=td Modem assert in file dspintisr.c at line 460 exp= (FALSE) INFO=[DSP assert 0x1 002,0X1,0XA,0X5565]
02-25 10:08:02.041 137 393 D Modemd:modem assert happen

As in the log message

The first line indicates which line of the modem part of the file has an execution exception,

The second line indicates that the modem assert exception occurred.


CASE9: How to analyze the problems related to call anomalies

In the indoor or outfield test, there are often problems such as phone call failure, telephone inability to answer, and dropped words during the call, and the "At^dsci" in the Android radio log can be used to analyze the normal process of the call and the switch of the call state.

The relevant parameters of the Dsci are described below, and the meaning of each return value representation can be referred to the official publication of the at Manual by Spreadtrum:
^dsci: <id>,<idr>,<stat>,<type>,<mpty>,<number>,<num_type>,[<bs_ Type>][,cause]
<id>: Call ID with a value of 1-7
<idr>: Distinguishing between calling and being called
<stat>: Indicates the status of the current phone, such as dialing, ringing, on, hanging off, etc.
<type>:voice call or data calling, usually voice calls (0)
<mpty>: Whether multiparty calls
<number>: To-end phone number
<num_type>: Type of number, refer to TS 24.008, usually without concern
[<bs_type>]: In cases where data call is applicable, there is usually no need to focus
[, cause]: Why the call hangs up

Case Log Analysis:

Dial 10086 number.

02-19 11:10:26.210 161 825 D at: [W] channel2:at> ATD10086;

Caller, call process, voice call, non-multiparty call, peer number 10086
02-19 11:10:26.280 161 365 D at: [W] channel0:at< ^dsci:1,0,2,0,0,10086,129

Caller, connect, voice call, non-multiparty call, peer number 10086
02-19 11:10:31.460 161 365 D at: [W] channel0:at< ^dsci:1,0,0,0,0,10086,129

Caller, hang up, voice call, non-multiparty call, peer number 10086, hang up reason 34 (bottom link exception)

02-19 11:10:56.520 161 365 D at: [W] channel0:at< ^dsci:1,0,6,0,0,10086,129,,34


Case10: 10-second protection mechanism for screenshot function

10-second protection mechanism for screenshot function

1.10-second protection of the screenshot function:
File: Phonewindowmanager.java (Frameworks\base\policy\src\com\android\internal\policy\impl) The
Phonewindowmanager.takescreenshot () function has the following code:
             if (Mcontext.bindservice (intent, Conn, context.bind_auto_create)) {
                 mscreenshotconnection = conn;
                Mhandler.postdelayed (Mscreenshottimeout, 10000);
           }
The main function of the code is bind on Takescreenshotservice, timed 10 seconds, if 10 seconds did not complete the screenshot, Phonewindowmanager will actively close takescreenshotservice.

2. Problems that may occur when the system is busy
  a. The screenshot function is not completed and no error is made.
  B. An error similar to the following may be reported and cause systemui (System user interface) to exit.
  If the system is very busy and the screenshot is not completed within 10 seconds, Phonewindowmanager actively shuts down the takescreenshotservice.
  Takescreenshotservice is going through the destroy process and is ready to exit when many states are already incorrect. At this time globalscreenshot to display screenshots and other operations, it may be wrong.
    androidruntime:fatal exception:main
    java.lang.IllegalStateException: This view must is attached to a window first
     at android.view.View.buildLayer (view.java:12119 )
     at Com.android.systemui.screenshot.globalscreenshot$3.run (Globalscreenshot.java : 471)
     at android.os.Handler.handleCallback (handler.java:615)
     at android.os.Handler.dispatchMessage (handler.java:92)
     at Android.os.Looper.loop (looper.java:137)
     at Android.app.ActivityThread.main ( activitythread.java:4973)

3. Impact and Countermeasures.
Does not affect the next screenshot operation.
The systemui can be restarted immediately after exiting, without affecting the subsequent operation.
In order to reduce the chance of error, you can increase the timing time. For example, 15 seconds.
Mhandler.postdelayed (mscreenshottimeout, 15000);


CASE11: How to get a quick and easy way to get the code to call order?

Sometimes the process of single-step debugging is difficult to do, but also need to understand the specific code call order, you can add the following code at the specific code, print the call stack information

RuntimeException e = new RuntimeException ("string");
E.fillinstacktrace ();
SLOG.E (TAG, "string", e);



Android Source problem solution (Exception handling)

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.