Android dropbox提供了一种保存日志的机制,支持将内核、Native、Java多种日志保存在"/data/system/dropbox"目录中。
两个主要的类是DropBoxManager和IDropBoxManagerService。
通过研究相关代码发现,当系统出现app crash,app anr ,system reboot .system boot,lowmem以及watchdog相关问题时,会触发android.intent.action.DROPBOX_ENTRY_ADDED。
故可以监听此action,进行对应日志的处理。
主要逻辑:
AndroidManifest.xml
注册监听:
android:name=".DropBoxReceiver"
android:enabled="true"
android:exported="true" >
访问相关日志需要权限:
DropBoxReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.os.DropBoxManager;
import java.io.File;
import com.sykean.mail.SendMailUtil;
import android.os.SystemProperties;
public class DropBoxReceiver extends BroadcastReceiver{
public static String TAG = "DropBoxReceiver";
@Override
public void onReceive(Context context, Intent intent) {
String tag = (String)intent.getExtras().get(DropBoxManager.EXTRA_TAG);
long time = (Long)intent.getExtras().get(DropBoxManager.EXTRA_TIME);
Log.d(TAG,"dropbox tag ="+tag+",time = "+time);
sendMail(tag,time);
}
public void sendMail(String tag,long time){
String sn = SystemProperties.get("sys.serialno","ABCDEF0123456789");
File file = null ;
if("system_app_crash".equals(tag)||"system_app_anr".equals(tag)){
file = new File("/data/system/dropbox/"+tag+"@"+time+".txt");
}
if (tag.endsWith("crash")) {
Log.d(TAG,"crash issue ");
} else if (tag.endsWith("anr")) {
Log.d(TAG,"anr issue ");
} else if (tag.endsWith("wtf")) {
Log.d(TAG,"wtf issue ");
} else if (tag.endsWith("watchdog")) {
Log.d(TAG,"watchdog issue ");
} else if (tag.equals("SYSTEM_BOOT")) {
Log.d(TAG,"SYSTEM_BOOT issue ");
} else if (tag.equals("SYSTEM_RESTART")) {
Log.d(TAG,"SYSTEM_RESTART issue ");
} else if (tag.endsWith("lowmem")) {
Log.d(TAG,"lowmem issue ");
}
if(file!=null){
if(!file.exists()){
Log.d(TAG,"file:"+"/data/system/dropbox/"+tag+"@"+time+".txt is not exist");
return;
}
SendMailUtil.sendMailSSL(file,"device "+sn+" mail the issue:"+tag+"@"+time+".txt","The issue is attached.");
}
}
}
SendMailUtil 这个工具类主要封装邮件发送能,后续文章介绍相关实现。