我正在构建一个未读的短信中继应用程序。有电话A和B,当A收到短信而没有人看过它时,我的应用程序将其转发给B.但我发现当A收到短信时,会显示一个系统通知。我的ContentObserver
onChange()
方法仅在我取消通知后才会调用。收到短信后我该怎么做才能收到未读短信?
ContentObserver:
public NewIncomingContentObserver(Handler handler, Application
application) {
super(handler);
this.mApplication = application;
}
@Override
public void onChange(boolean selfChange) {
System.out.println(selfChange);
super.onChange(selfChange);
Uri uri = Uri.parse(SMS_URI_INBOX);
mMessageListener.OnReceived(this.getSmsInfo(uri, mApplication));
}
/**
* get the newest SMS
*/
private SmsInfo getSmsInfo(Uri uri, Application application) {
...
}
public interface MessageListener {
public void OnReceived(SmsInfo smsInfo);
}
public void setOnReceivedMessageListener(
MessageListener messageListener) {
this.mMessageListener = messageListener;
}
}
服务:
public class SmsListenerService extends Service {
public static final String URI = "content://sms/inbox";
public SmsListenerService() {
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Register observer
NewIncomingContentObserver smsContentObserver =
new NewIncomingContentObserver(new Handler(), getApplication());
this.getContentResolver().registerContentObserver
(Uri.parse(URI), true, smsContentObserver);
smsContentObserver.setOnReceivedMessageListener(new NewIncomingContentObserver.MessageListener() {
@Override
public void OnReceived(SmsInfo smsInfo) {
System.out.println(smsInfo);
}
});
return START_NOT_STICKY;
}
}
答案 0 :(得分:0)
借用(https://github.com/Pyo25/Phonegap-SMS-reception-plugin)的示例,示例是一个phonegap插件,但您仍然可以使用它:
public class SmsReceiver extends BroadcastReceiver {
public static final String SMS_EXTRA_NAME = "pdus";
// This broadcast boolean is used to continue or not the message broadcast
// to the other BroadcastReceivers waiting for an incoming SMS (like the native SMS app)
private boolean broadcast = false;
@Override
public void onReceive(Context ctx, Intent intent) {
// Get the SMS map from Intent
Bundle extras = intent.getExtras();
if (extras != null)
{
// Get received SMS Array
Object[] smsExtra = (Object[]) extras.get(SMS_EXTRA_NAME);
for (int i=0; i < smsExtra.length; i++)
{
SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);
String formattedMsg = sms.getOriginatingAddress() + ">" + sms.getMessageBody();
}
// If the plugin is active and we don't want to broadcast to other receivers
if (!broadcast) {
this.abortBroadcast();
}
}
}
}
在我的AndroidManifest中:
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
答案 1 :(得分:0)
我认为短信收件箱是由特定的短信应用管理的。因此,通过content://sms/inbox
收听新短信是我的应用程序中特定于SMS应用程序的解决方案。 @Niels的回答可能是更好的解决方案。