Android应用监听来电、短信等方法

时间:2022-08-27 08:56:28

这功能最好放在一个Service中,在需要的地方启动这个Service即可。直接上代码吧:

/**
* 检测来电、短信
*/

public class NotificationMonitorService extends Service {
private static final String TAG = "NotificationMonitor";
private static final String APP_PACKAGE_SMS = "com.android.mms";
private static final String APP_PACKAGE_CALL = "com.android.server.telecom";

private enum State {
STATE_UNRINGING, STATE_RINGING,
}
private State mCurrentState = State.STATE_UNRINGING;

@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "service create");
//监听短信的广播接收者
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(broadcastReceiver, intentFilter);

// 监听来电
TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
telephonyManager.listen(customerPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}

// START_STICKY:如果service进程被kill掉,保留service的状态为开始状态,但不保留递送的intent对象。随后系统会尝试重新创建service,由于服务状态为开始状态,所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。如果在此期间没有任何启动命令被传递到service,那么参数Intent将为null。
// START_NOT_STICKY:“非粘性的”。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统不会自动重启该服务。
// START_REDELIVER_INTENT:重传Intent。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入。
// START_STICKY_COMPATIBILITY:START_STICKY的兼容版本,但不保证服务被kill后一定能重启。
// 创建页面用来启动Services,布局:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null) {
Log.e(TAG, "Intent is null in onStartCommand: ", new NullPointerException());
return Service.START_NOT_STICKY;
}
return Service.START_REDELIVER_INTENT;

}

@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "service destory");
unregisterReceiver(broadcastReceiver);
}

/**
* 检测来电
*/

private PhoneStateListener customerPhoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
String contactName;
Reminder reminder;
if (Pw3Setting.getCallReminder()){
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
Log.d(TAG, "CALL_STATE_IDLE");
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d(TAG, "CALL_STATE_OFFHOOK!!!!!!!!!!");
if (State.STATE_UNRINGING == mCurrentState) {
return;
}
mCurrentState = State.STATE_UNRINGING;
contactName = getContactNameFromPhoneNum(getApplicationContext(), incomingNumber);
Log.d(TAG, "contactName===" + contactName);
reminder = new Reminder(Reminder.RmdrTypeEnum.HANG_UP);
reminder.setName(contactName);
reminder.setNumber(incomingNumber);
//监听到了挂断电话,进行相应的操作
SendMsgMgr.getInstance().sendIncomingCall(reminder, new IRspListener() {
@Override
public void onSuccess(Object object) {
Log.i(TAG,"set hang up call reminder success");
}

@Override
public void onFailed(int errorCode) {
Log.e(TAG,"set hang up call reminder failed");
}
});
break;
case TelephonyManager.CALL_STATE_RINGING:
Log.d(TAG, "CALL_STATE_RINGING!!!!!!!!!!");
if (State.STATE_RINGING == mCurrentState) {
return;
}
Log.d(TAG, "CALL_STATE_RINGING");
// 根据号码获取联系人姓名
contactName = getContactNameFromPhoneNum(getApplicationContext(), incomingNumber);
Log.d(TAG, "contactName===" + contactName);
mCurrentState = State.STATE_RINGING;
reminder = new Reminder(Reminder.RmdrTypeEnum.INCOMING_CALL);
reminder.setNumber(incomingNumber);
reminder.setName(contactName);
//监听到了来电,进行相应的操作
SendMsgMgr.getInstance().sendIncomingCall(reminder, new IRspListener() {
@Override
public void onSuccess(Object object) {
Log.i(TAG,"set inCome call reminder success");
}

@Override
public void onFailed(int errorCode) {
Log.e(TAG,"set inCome call reminder failed");
}
});
break;
default:
mCurrentState = State.STATE_UNRINGING;
break;
}
}
}
};

/**
* 通过电话号码获取姓名
*/

public String getContactNameFromPhoneNum(Context context, String phoneNum) {
String contactName = "stranger";
{
if (phoneNum != null){
phoneNum.trim();
}
// 处理电话号码格式问题
ContentResolver cr = context.getContentResolver();
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (pCur.moveToNext()) {
String s = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
s = remove(s, ' ');
if (s.contains(phoneNum) || phoneNum.contains(s)) {
contactName = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
break;
}
}
pCur.close();
}
return contactName;
}

// 去掉空格
public String remove(String resource, char ch) {
StringBuffer buffer = new StringBuffer();
int position = 0;
char currentChar;
while (position < resource.length()) {
currentChar = resource.charAt(position++);
if (currentChar != ch)
buffer.append(currentChar);
}
return buffer.toString();
}

/**
监听收到短信的广播
*/

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Log.d(TAG, "android.provider.Telephony.SMS_RECEIVED");
Object[] pduses = (Object[]) intent.getExtras().get("pdus");
if (pduses == null) {
return;
}
for (Object pdus : pduses) {
//获取短信的内容
byte[] pdusmessage = (byte[]) pdus;
SmsMessage sms = SmsMessage.createFromPdu(pdusmessage);
String mobile = sms.getOriginatingAddress();//发送短信的手机号码
String content = sms.getMessageBody(); //短信内容
Date date = new Date(sms.getTimestampMillis());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = format.format(date); //得到发送时间
String contactName = getContactNameFromPhoneNum(getApplicationContext(), mobile);
Reminder reminder = new Reminder(Reminder.RmdrTypeEnum.SMS_RCV);
if (contactName.equals("stranger")){
contactName = mobile;
}
reminder.setName(contactName);
reminder.setNumber(mobile);
//reminder.setTxtContent(content);
reminder.setTxtContent("New message demo");
//监听收到短信,进行相应的操作
SendMsgMgr.getInstance().setSMSReminder(reminder, new IRspListener() {
@Override
public void onSuccess(Object object) {
Log.i(TAG, "set sms reminder success");
}
@Override
public void onFailed(int errorCode) {
Log.e(TAG, "set sms reminder failed");
}
});
}
}
}
};

}