Android write behavior log to SD card concurrent processing asynchronous write data to file does not affect interface response time

Source: Internet
Author: User


The company is doing a project that requires recording user behavior, writing behavior log files to the SD card. The realization of the idea does not affect the user experience of the interface, the record log must always be missing.

1. Concurrent processing log write a class is responsible for managing the log data passed by each thread, and the log data is placed in the queue waiting for the write thread to process. Each time you add a log data, it checks to see if the Write log thread is working, and the data passed in for concurrent processing takes synchronized synchronization:

concurrentlinkedqueue is a thread-safe queue based on a linked node. Concurrent access does not require synchronization. Because it adds elements to the end of the queue and removes them from the head, Concurrentlinkedqueue shared access to public collections works fine as long as you don't need to know the size of the queue. Gathering information about the size of the queue is slow and needs to be traversed the queue is recommended to use if (!queue.isempty ()) to determine if 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.concurrentlinkedqueue;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);p ublic static String filepath= "";p UB     Lic static concurrentlinkedqueue tempqueue=new concurrentlinkedqueue<object> ()/** * Record basic information header * @param bi        */public static synchronized void Recordbaseinfolog (Baseinfo bi) {tempqueue.add (BI); if (!     writethread.iswritethreadlive) {//monitor if the write thread is working, no then 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 log file and write to log * * @return * **/public static void Recordstringlog (String text) {//Create new or open log file = new file (f Ilepath), if (!file.exists ()) {File.getparentfile (). mkdirs (); try {file.createnewfile ();} catch (IOException e) { Logger.error ("Behavior log:" +filepath+ "failed to create the file!)  "); E.printstacktrace ();}} try {FileWriter filerwriter = new FileWriter (file, true);//The following parameter indicates whether to connect the original data in the file, not overwrite bufferedwriter bufwriter = new BufferedWriter (Filerwriter); bufwriter.write (text); Bufwriter.newline (); Bufwriter.close (); Filerwriter.close (); LOG.D ("Behavior log write succeeded", text);} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} /** * Determine if 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. asynchronously writing data to a file does not affect the user experience and cannot be delayed because of writing logs. (In the experiment if the data in the file is small, even if the synchronous write is not too slow) in order to achieve this purpose first consider multithreading another thread is specifically responsible for writing the log into the file in the code as follows:

Package Com.xx.log;import Com.google.gson.gson;public class Writethread extends Thread{public static Boolean iswritethreadlive=false;//writes whether the log thread is already running public writethread () {iswritethreadlive=true;} @Overridepublic void Run () {iswritethreadlive=true; Gson gson=new Gson ();       while (! ActionLog.tempQueue.isEmpty ()) {//Pair column not empty when try {//write log to sd card Actionlog.recordstringlog (Gson.tojson ( ActionLog.tempQueue.poll ())); } catch (Exception e) {e.printstacktrace ();}}    iswritethreadlive=false;//the logs in the queue are all finished, close the thread (you can always open the test)}}

Actually, I think it might be better to keep the thread running, and the frequent creation of thread objects should also be costly.

Okay, all right. The above code has been tested to reach a large number of concurrent write logs of multiple threads, which can be guaranteed to be written sequentially to the file without affecting the user experience response time user feels negligible

Because of the time problem I have to write the processing of the upload log, the function of writing log for the time being, after the study to keep the writing thread has been live until the end of the program. There is also the need to improve how much performance has been tested.


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.