我正在尝试在 android 上创建一个应用程序,我需要在其中像时尚一样在聊天中显示消息。我一直在阅读 SMS 的 4.4 API,但我似乎无法弄清楚如何使用它们。目前,我只收到来自 sms.Inbox 内容提供商的消息。 谁能告诉我在哪里可以看到一些有关如何有效使用它们的示例?
最佳答案
使用BroadcastReceiver
在手机收到短信时进行广播,如下所示:
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras == null)
return;
// To display a Toast whenever there is an SMS.
// Toast.makeText(context,"Recieved",Toast.LENGTH_LONG).show();
Object[] pdus = (Object[]) extras.get("pdus");
for (int i = 0; i < pdus.length; i++) {
SmsMessage SMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
String sender = SMessage.getOriginatingAddress();
String body = SMessage.getMessageBody().toString();
// A custom Intent that will used as another Broadcast
Intent in = new Intent("SmsMessage.intent.MAIN").putExtra(
"get_msg", sender + ":" + body);
// You can place your check conditions here(on the SMS or the
// sender)
// and then send another broadcast
context.sendBroadcast(in);
// This is used to abort the broadcast and can be used to silently
// process incoming message and prevent it from further being
// broadcasted. Avoid this, as this is not the way to program an
// app.
// this.abortBroadcast();
}
}
关于Android:使用 android.provider.Telephony.Sms.Conversations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24841978/