来自SmsListener类的活动的TextView

时间:2014-09-26 23:09:29

标签: android textview

我有用于捕获SMS的Sms Listener类,我在我的主Activity中有TextView,在收到传入短信后我需要在主要活动中更新TextView

    public class SmsListener extends BroadcastReceiver{


        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub

            if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
                Bundle bundle = intent.getExtras();         
                SmsMessage[] msgs = null;
                String msg_from;
                if (bundle != null){
                    try{
                        Object[] pdus = (Object[]) bundle.get("pdus");
                        msgs = new SmsMessage[pdus.length];
                        for(int i=0; i<msgs.length; i++){
                            msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                            msg_from = msgs[i].getOriginatingAddress();
                            String msgBody = msgs[i].getMessageBody();

there i want update TextView on my Main activity
                        }
                    }catch(Exception e){
    //                            Log.d("Exception caught",e.getMessage());
                    }
                }
            }
        }
    }

帮帮我

1 个答案:

答案 0 :(得分:0)

在MainActivity中初始化MainActivity类的变量,如下所示。

public class MainActivity extends Activity {
 private static MainActivity ins;
protected void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
ins = this;     
}

public static MainActivity  getInstace()
{
     return ins;
}
public void updateTheTextView(final String t) {
MainActivity.this.runOnUiThread(new Runnable() {
    public void run() {
        TextView textV1 = (TextView) findViewById(R.id.textV1);
        textV1.setText(t);
    }
 });
}
}


 public class NotifAlarm extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
          try {
            MainActivity  .getInstace().updateTheTextView("String");
        } catch (Exception e) {

        }

     }
 }