Android +短信接收器+ Toast = FAIL

时间:2010-08-06 04:36:47

标签: android toast

我正在尝试将此代码用于我的Dell Streak,但是当我收到短信时,我仍然没有收到Toast通知...我在manifest.xml文件中添加了'receive'标签...我我是一个完整的菜鸟,需要一点帮助才能开始:)

package net.learn2develop.SMSMessaging;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SMSReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();       
        SmsMessage[] msgs = null;
        String str = "";           
        if (bundle != null)
        {
            //---retrieve the SMS message received---
            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]);               
                str += "SMS from " + msgs[i].getOriginatingAddress();                     
                str += " :";
                str += msgs[i].getMessageBody().toString();
                str += "\n";       
            }
            //---display the new SMS message---
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        }                         
    }
}

1 个答案:

答案 0 :(得分:1)

您不应该从非UI组件创建Toast。您应该只从Toast创建ActivityToast未显示的原因是因为BroadcastReceiver未在具有LooperToast的线程上运行,取决于它,以及其中包含的内容设置UI线程。 Notifications用于非UI组件通知用户。