how to write exception in log file using android?

后端 未结 2 616
萌比男神i
萌比男神i 2021-01-07 13:40

I want to write text file in sd card when I get an exception from my application

How to implement this concept in my application?

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-07 13:55

    A general way to go about this, although in practice you should use buffered streams whenever possible.

    In your onCreate(Bundle savedInstanceState) callback or anywhere else you want to do this logging:

    try
    {
    //normal application code
    
    }
    //called whenever an Exception is thrown
    catch(Exception e)
    {
    //stream for writing text
    FileWriter writer=null;
    try
    {
        writer = new FileWriter(this.getExternalFilesDir());
        //write to the SD card
    } catch(Throwable t) {}
    finally
    {
        if(writer != null) writer.close();
    }
    
    }
    

    Note that I omitted checking for the SD card, but you should always do this. See http://developer.android.com/guide/topics/data/data-storage.html#filesExternal

    Sorry for the crappy code formatting. This little text box is nothing like Eclipse.

提交回复
热议问题