如何同时使用BroadcastReceiver& ListActivity在相同的代码中

时间:2012-08-06 05:43:51

标签: android android-listview broadcastreceiver

此项目需要两个类。

  • BroadcastReceiver(上课) - 接收短信;
  • ListActivity(课程) - 显示短信;

由于setListAdapter()方法需要定义ListActivity(类),我的问题是如何在以下代码中定义这两个类?

import ....
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();                      
        }

        //----REQUIRE ListActivity(class) to define----//
        // how should i define the class here???

        //---display in list---
        setListAdapter(new ArrayAdapter<String>(this, R.layout.main,str));
        ListView listView = getListView();
        listView.setTextFilterEnabled(true);

        //---method is call when listitem is clicked---
        listView.setOnItemClickListener(new OnItemClickListener() {
            //described method
        });
    }                         
}

2 个答案:

答案 0 :(得分:2)

根据我的最简单的解决方案是:

  • 1将所有项目存储在扩展BroadcastReceiver

  • 的课程列表中
  • 2将带有Intent的列表传递给扩展ListActivity

答案 1 :(得分:1)

Kin,您还可以在不扩展列表视图的活动中设置列表视图。请参阅此example