2 s39014971 s39014971 于 2016.03.13 16:32 提问

Android 接收短信功能

package com.example.smstest;

import javax.security.auth.PrivateCredentialPermission;

import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.gsm.SmsMessage;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

private TextView sender;
private TextView content;
private IntentFilter receiveFilter;
private MessageReceiver messageReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sender=(TextView)findViewById(R.id.sender);
    content=(TextView)findViewById(R.id.content);
    receiveFilter=new IntentFilter();
    Log.v("sss","success0");
    receiveFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
    Log.v("sss","success1");
    messageReceiver=new MessageReceiver();
    Log.v("sss","success2");
    registerReceiver(messageReceiver,receiveFilter);
    Log.v("sss","success3");
}
 class MessageReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Log.v("sss","success4");
        Bundle bundle=intent.getExtras();//从intent中取出一个bundle对象
        Object[] pdus=(Object[])bundle.get("pdus");
        //提取短信消息使用pdus密钥提取一个SMS pdus数组;
        SmsMessage[] messages=new SmsMessage[pdus.length];

        //将每一字节数组转换为SmsMessage对象

        for(int i=0;i<messages.length;i++)
        {
            messages[i]=SmsMessage.createFromPdu((byte[])pdus[i]);
        }
        String address=messages[0].getOriginatingAddress();
        //调用message对象的getOriginatingAddress()方法
        //获取发送方号码;
        String fullMessage=" ";
        for(SmsMessage message: messages)
        {
            fullMessage+=message.getMessageBody();//获取短信内容将短信内容拼接起来
        }
        sender.setText(address);//显示在TextView上
        content.setText(fullMessage);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    unregisterReceiver(messageReceiver);
}

}

1个回答

s39014971
s39014971   2016.03.13 16:35
已采纳

定义了两个Textview为什么收到短信之后程序界面没有显示

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!