client_Hale
2018-08-21 2a4727a346fef2ae347e1bad707f359e7be73b9c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
package com.secondworld.univeralsdk;
 
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Looper;
import android.os.SystemClock;
import android.widget.Toast;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 
/**
 * Created by Administrator on 2018/7/19 0019.
 */
 
public class CrashCatchUtil implements Thread.UncaughtExceptionHandler
{
    private static final String TAG = "CrashCatchUtil";
    private Context m_Context;
    private Thread.UncaughtExceptionHandler m_UncaughtExceptionHandler;
    private Map<String, String> m_DevicceInfo = new HashMap<>();
 
    private CrashCatchUtil() {}
 
    private static CrashCatchUtil m_Instance;
 
    public static CrashCatchUtil getInstance()
    {
        if (m_Instance == null)
        {
            m_Instance = new CrashCatchUtil();
        }
        return m_Instance;
    }
 
    public void init(Context context)
    {
        m_Context = context;
        m_UncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
        autoClear(5);
    }
 
    @Override
    public void uncaughtException(Thread thread, Throwable throwable)
    {
        if (!handleException(throwable) && m_UncaughtExceptionHandler != null)
        {
            m_UncaughtExceptionHandler.uncaughtException(thread, throwable);
        }
        else
        {
            SystemClock.sleep(3000);
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }
    }
 
    private void recordDeviceInfo()
    {
        m_DevicceInfo.clear();
        m_DevicceInfo.put("brand", Build.BRAND);
        m_DevicceInfo.put("model", Build.MODEL);
        m_DevicceInfo.put("android_version", String.valueOf(Build.VERSION.SDK_INT));
        try
        {
            PackageManager _pkgMgr = m_Context.getPackageManager();
            PackageInfo _pkgInfo = _pkgMgr.getPackageInfo(m_Context.getPackageName(),
                                                          PackageManager.GET_ACTIVITIES);
            if (_pkgInfo != null)
            {
                m_DevicceInfo.put("versionName", _pkgInfo.versionName);
                m_DevicceInfo.put("versionCode", String.valueOf(_pkgInfo.versionCode));
            }
        } catch (PackageManager.NameNotFoundException e)
        {
            e.printStackTrace();
        }
    }
 
    private boolean handleException(Throwable throwable)
    {
        if (throwable == null)
        {
            return false;
        }
 
        try
        {
            new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    Looper.prepare();
                    Toast.makeText(m_Context, "程序出现异常,即将重启", Toast.LENGTH_LONG).show();
                    Looper.loop();
                }
            }).start();
 
            recordDeviceInfo();
 
            save(throwable);
 
            SystemClock.sleep(3000);
 
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return true;
    }
 
    private String save(Throwable throwable) throws Exception
    {
        StringBuffer sb = new StringBuffer();
        try
        {
            SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = sDateFormat.format(new Date());
            sb.append("\r\n" + date + "\n");
            for (Map.Entry<String, String> entry : m_DevicceInfo.entrySet())
            {
                String key = entry.getKey();
                String value = entry.getValue();
                sb.append(key + "=" + value + "\n");
            }
 
            Writer writer = new StringWriter();
            PrintWriter printWriter = new PrintWriter(writer);
            throwable.printStackTrace(printWriter);
            Throwable cause = throwable.getCause();
            while (cause != null)
            {
                cause.printStackTrace(printWriter);
                cause = cause.getCause();
            }
            printWriter.flush();
            printWriter.close();
            String result = writer.toString();
            sb.append(result);
 
            String fileName = writeFile(sb.toString());
            return fileName;
        } catch (Exception e)
        {
            sb.append("写入崩溃日志时, 出现了异常状况...\r\n");
            writeFile(sb.toString());
        }
        return null;
 
    }
 
    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
 
    private String writeFile(String sb) throws Exception
    {
        String time = formatter.format(new Date());
        String fileName = "crash-" + time + ".log";
        String path = getPath();
        File dir = new File(getPath());
        if (!dir.exists())
        {
            dir.mkdirs();
        }
        FileOutputStream fos = new FileOutputStream(path + fileName, true);
        fos.write(sb.getBytes());
        fos.flush();
        fos.close();
        return fileName;
    }
 
    private String getPath()
    {
        return m_Context.getExternalFilesDir("").getAbsolutePath()
                + File.separator
                + "crash"
                + File.separator;
    }
 
    /**
     * 文件删除
     *
     * @param autoClearDay 文件保存天数
     */
    public void autoClear(final int autoClearDay)
    {
        delete(getPath(), new FilenameFilter()
        {
            @Override
            public boolean accept(File file, String filename)
            {
                String s = FileUtil.getFileNameWithoutExtension(filename);
                int day = autoClearDay < 0 ? autoClearDay : -1 * autoClearDay;
                String date = "crash-" + getOtherDay(day);
                return date.compareTo(s) >= 0;
            }
        });
    }
 
    private void delete(String path, FilenameFilter filter)
    {
        File _file = new File(path);
        if (!_file.exists())
        {
            return;
        }
        File[] _files = _file.listFiles(filter);
        for (int i = _files.length - 1; i >= 0; i--)
        {
            _files[i].delete();
        }
    }
 
    private String getOtherDay(int offset)
    {
        Calendar _calendar = Calendar.getInstance();
        _calendar.add(Calendar.DATE, offset);
        return formatter.format(_calendar.getTime());
    }
}