Android write behavior log to SD card concurrent processing asynchronous Writing of data to files does not affect interface Response Time

Source: Internet
Author: User


The company is working on a project to record user behavior and write behavior log files to the SD card.The idea of implementation does not affect the user experience on the interface. Logs must be recorded from time to time and cannot be missed.

1. Concurrent log processing write a class is responsible for managing the log data transmitted by each thread. The log data is placed in the queue and waiting for the write thread to process. Each time a log data is added here, the log writing thread will check whether it is working. At the same time, synchronized synchronization is used for concurrent processing of transmitted data:

Concurrentincluqueue is a thread-safe Queue Based on Link nodes. Concurrent access does not need to be synchronized. Because it adds elements to the end of the queue and deletes them from the header, as long as you do not need to know the queue size, concurrentqueue queue can work well on shared access to public sets. It is slow to collect information about the queue size. You need to traverse the queue.Recommended If (! Queue. isEmpty () to determine whether it is null

Package com. xx. log; import java. io. bufferedWriter; import java. io. file; import java. io. fileWriter; import java. io. IOException; import java. text. simpleDateFormat; import java. util. arrayList; import java. util. calendar; import java. util. date; import java. util. concurrent. concurrent1_queue; import org. apache. log4j. logger; import org. apache. log4j. spi. loggerFactory; import android. util. log;/*** behavior Log record * @ author Administrator **/public class ActionLog {protected final static Logger logger = Logger. getLogger (ActionLog. class); public static String filePath = ""; public static concurrent1_queue tempQueue = new concurrent1_queue();/*** Record the basic information header * @ param bi */public static synchronized void recordBaseInfoLog (BaseInfo bi) {tempQueue. add (bi); if (! WriteThread. isWriteThreadLive) {// check whether the write thread is working. If no, create new WriteThread (). start () ;}}/*** record behavior information * @ param ai */public static synchronized void recordActionInfoLog (ActionInfo ai) {tempQueue. add (ai); if (! WriteThread. isWriteThreadLive) {new WriteThread (). start () ;}}/*** open the log file and write the log ** @ return ***/public static void recordStringLog (String text) {// create or open a log File file = new File (filePath); if (! File. exists () {file. getParentFile (). mkdirs (); try {file. createNewFile ();} catch (IOException e) {logger. error ("behavior log: failed to create file in" + filePath +! "); E. printStackTrace () ;}try {FileWriter filerWriter = new FileWriter (file, true); // The following parameter indicates whether to connect the original data in the file, do not overwrite BufferedWriter bufWriter = new BufferedWriter (filerWriter); bufWriter. write (text); bufWriter. newLine (); bufWriter. close (); filerWriter. close (); Log. d ("behavior log written successfully", text);} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}}/*** determines whether the log File exists * @ return */public static boolean isExitLogFile () {file File = new file (filePath); if (File. exists () & file. length ()> 3) {return true;} else {return false;}/*** Delete Log File */public static void deleteLogFile () {File file = new File (filePath); if (file. exists () {file. delete ();}}}

2. writing data to a file asynchronously does not affect user experience, and there cannot be any latency due to log writing. (In this experiment, if the data written to a file is small at a time, it will not be too slow even if the data is synchronized) to achieve this goal, we first consider multithreading. Another thread is responsible for writing logs to files using the following code:

Package com. xx. log; import com. google. gson. gson; public class WriteThread extends Thread {public static boolean isWriteThreadLive = false; // whether the log writing Thread is already running public WriteThread () {isWriteThreadLive = true;} @ Overridepublic void run () {isWriteThreadLive = true; Gson gson = new Gson (); while (! ActionLog. tempQueue. isEmpty () {// when the column is not empty, try {// write the log to the SD card ActionLog. recordStringLog (gson. toJson (ActionLog. tempQueue. poll ();} catch (Exception e) {e. printStackTrace () ;}} isWriteThreadLive = false; // The logs in the queue are all written, and the thread is closed (you can also open it for testing )}}

In fact, I think it may be better to keep the write thread running. Frequent thread object creation may also consume a lot of performance.

After testing the above Code, a large number of concurrent logs can be written in multiple threads, which ensures that logs are written to files in order without affecting the user experience.

Due to time issues, I still need to write the processing of uploaded logs. This is the first way to write logs. Later I have time to study and keep the write thread live until the entire program ends. There is also a need to test how much performance can be improved.


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.