Skip to content

Instantly share code, notes, and snippets.

@fyhack
Created September 6, 2015 07:29
Show Gist options
  • Save fyhack/53d493beff134fbbf33c to your computer and use it in GitHub Desktop.
Save fyhack/53d493beff134fbbf33c to your computer and use it in GitHub Desktop.
捕获ANR(在android4.4通过)
<service android:name=".ANRBroadcastService" android:process=":anrwatch" />
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import org.acra.ACRA;
import java.util.Set;
/**
* 捕获ANR 调用ACRA上报
*
* Created by fyhack on 6/18/15.
*/
public class ANRBroadcastService extends Service {
private static final String TAG = "ANRBroadcastService";
static final String ACTION_ANR = "android.intent.action.ANR";
private MyReceiver myRec;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onStart(Intent intent, int startId) {
Log.d(TAG,"onStart");
super.onStart(intent, startId);
}
@Override
public void onDestroy() {
Log.d(TAG,"onDestroy");
unregisterReceiver(myRec);
super.onDestroy();
}
@Override
public void onCreate() {
Log.d(TAG, "onCreate");
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_ANR);
myRec = new MyReceiver();
registerReceiver(myRec, filter);
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG,"intent:" + intent);
if (intent.getAction().equals(ACTION_ANR))
{
System.out.println("MyReceiver -----ANR ---------");
System.out.println("package:"+intent.getPackage());
System.out.println("dataString:"+intent.getDataString());
System.out.println("component:"+intent.getComponent());
Bundle bundle = intent.getExtras();
Set<String> keySet = bundle.keySet();
for(String key : keySet){
System.out.println(String.valueOf(bundle.get(key)));
}
Exception caughtException = new Exception("ANR !!!");
// ACRA.getErrorReporter().handleException(caughtException);
ACRA.getErrorReporter().handleSilentException(caughtException);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment