我正在编写一个删除通话记录的应用程序。这是代码
public class PhoneStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
System.out.println("Receiver start");
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
Toast.makeText(context, "Call Idle State"+incomingNumber, Toast.LENGTH_SHORT).show();
DeleteCallLogByNumber("97********");
Toast.makeText(context, "Log deleted", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void DeleteCallLogByNumber(String number) {
String queryString = "NUMBER=" + number;
if (ActivityCompat.checkSelfPermission(MainActivity.Context(), Manifest.permission.WRITE_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
return;
}
MainActivity.ContentResolver().delete(CallLog.Calls.CONTENT_URI, queryString, null);
}
}
我的异常是
java.lang.NullPointerException:尝试调用虚方法' int android.content.Context.checkPermission(java.lang.String,int,int)'在空对象引用上
答案 0 :(得分:0)
我自己想出来了
public class PhoneStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
System.out.println("Receiver start");
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
Toast.makeText(context, "Call Idle State"+incomingNumber, Toast.LENGTH_SHORT).show();
DeleteCallLogByNumber("97********", context);
Toast.makeText(context, "Log deleted", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void DeleteCallLogByNumber(String number, Context context) {
String queryString = "NUMBER='" + number+"'";
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
return;
}
context.getContentResolver().delete(CallLog.Calls.CONTENT_URI, queryString, null);
}
}