Android realizes multiple flash-back purge data _android

Source: Internet
Author: User
Tags exception handling tojson

Most of the time, the unexpected data returned by the background may cause the app to flash back. If the exception data is cached locally by the app, the flash will occur even if the process is restarted. The only solution is to clear the app data, but the user may not be able to use it without this awareness or trouble, which is unacceptable to us. In the use of Taobao, chasing books, such as the app when I found that sometimes they will continue to flash back, but often three times after the flash back to normal, so the general mature app will do a continuous flash three times after the work of clearing the cached data. At present, I do not find any blog to talk about this matter, so let me say this matter, for the hope of improving the app user experience to provide a little reference to friends.

ACRA
To be able to do something at the time of the flash, we can use Acra, an open source project on GitHub that allows users to set some sender to do something when the app flashes. Specific use can refer directly to GitHub. If you do not want to use ACRA, you can also implement a uncachedexceptionhandler yourself and replace the system default handler, and deal with the data in this handler.

Implementing Purge Data
ACRA provides some of its own sender, such as Emailintentsender to send mail to a specified mailbox using a system mail client. And we want the implements Reportsender interface to record the number of flashes and erase the data.

public class Crashhandler implements Reportsender {
  @Override
  the public void Send (context context, crashreportdata Errorcontent) throws Reportsenderexception {
    timber.i ("Flash back, check if data needs to be emptied");
    New Crashmodel (). Checkandcleardata ();
  }
}

Here we have written a crashmodel to record the number of flashes and the time to decide whether to clear the data, as shown in the code below. We couldn't use sharedperferences to clean up the data because we couldn't open other threads at Reportsender (when we opened the SP, we actually opened a new thread). To do this, you need to find the location of the data cache and delete the file. In the same way, record flashback times can only be recorded by file. Of course, you can choose some files not to be deleted, such as user information, such as not easily problematic data.

public class Crashmodel {private static final String key_crash_times = "Crash_times";
  private static final String Crash_time_file_name = "Crash_time"; You cannot get the package name through App.getpackagename, otherwise there will be a problem and you can only default to Cn.campusapp.campus. So for the debug or operating version, the data will clear the release out of the private static final String File_dir = String.Format ("/data/data/%s/"),
  BUILDCONFIG.APPLICATION_ID);
  private static final String Account_file_name = String.Format ("%s%s", File_dir, "Shared_prefs/account_pref.xml"); private static arraylist<string> Files_dontneed_delete = new arraylist<> (); Files in this directory will not be deleted static {Files_dontneed_delete.add (account_file_name);//The current account information file will not be deleted, but will manually change the data, leaving only the UserID Accesstok
  En and school} protected arraylist<long> mcrashtimes;
  Gson Gson = new Gson ();

  Private File Mfiledir;
    Public Crashmodel () {mfiledir = new File (file_dir);
    Mcrashtimes = Readcrashtimes ();
      if (mcrashtimes = = null) {mcrashtimes = new arraylist<> (); Storecrashtimes (McrashtiMES);

    } public void Checkandcleardata () {Long timenow = System.currenttimemillis ();
      if (Checkcleardata (TimeNow, New arraylist<> (Mcrashtimes)) {timber.i ("has three flashes in 5 minutes, need to clean up data");
      try {cleardata ();
      catch (Exception e) {TIMBER.E (E, "Empty all data Failed");
      } else {mcrashtimes.add (timenow);
      Storecrashtimes (Mcrashtimes);
    TIMBER.I ("No need to empty data this time,%s", Gson.tojson (Mcrashtimes)); }} private void Storecrashtimes (arraylist<long> crashtimes) {try {String str = Gson.tojson (Crashti
      MES);
    Files.writetofile (Mfiledir, Crash_time_file_name, str);
    catch (Exception e) {TIMBER.E (E, Save flash time failed); } private arraylist<long> Readcrashtimes () {try {String timestr = files.readfilecontent (mfiledir
      , crash_time_file_name);
    Return Gson.fromjson (Timestr, New typetoken<arraylist<long>> () {}.gettype ()); catch (Exception e) {TiMBER.E (E, "read flicker Time failed");
  return null; /** * Check whether the need to clear the data, the current purge strategy is in 5 minutes there are three times the flash of the data, that is, from the forward traversal, as long as the first two flash back occurred within 5 minutes, on the empty data * * @return * * Private Boole
    An checkcleardata (long time, arraylist<long> crashtimes) {timber.i (Gson.tojson (crashtimes));
    int count = 0;
      for (int i = Crashtimes.size ()-1; I >= 0; i--) {Long crashtime = Crashtimes.get (i);
        if (time-crashtime <= 5 * 1000) {count++;
        if (Count >= 2) {break;
    ' If (Count >= 2) {//in 5 minutes There are three flashes, this time you need to empty the data return true;
    else {return false; }/** * Clears the data, including in the database and sharedpreferences * * @throws Exception/private void ClearData () throws exc
    eption {timber.i ("Start cleaning up data");
  Files.deletefilesexceptsomeindirectory (Mfiledir, files_dontneed_delete);
 }


}

Then we need to add Crashhandler to the ACRA exception handling sender list. Add the following code to your application class.

@ReportsCrashes (
  ///Some ACRA settings, specific reference Acra documentation, because we use custom sender, so there is no need to set
    //mailto = "bugs@treeholeapp.cn",
    //mode = reportinginteractionmode.toast,
    //restoasttext = r.string.crash_toast_text
) public
class APP extends Application {

  @Override public
  void OnCreate () {
   if (!) Buildconfig.debug) {//Here I judge that data is purged only when it is not DEBUG, primarily to keep threads in the process of development.
        Acra.init (application_context);
        Crashhandler handler = new Crashhandler ();
        Acra.geterrorreporter (). Setreportsender (handler); Check if you want to empty data}} on Flash


Summarize
Above that is to achieve a number of flash back to clear the implementation of data, I hope that you develop the app bug less and fewer.

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.