Android - 如何引用BroadcastReceiver中注册接收者的活动?

时间:2014-03-21 20:35:58

标签: android android-activity broadcastreceiver

在我的MainActivity中,我有:

this.registerReceiver(new SmsListener(),new IntentFilter("RECEIVED SMS"));

在我的manifest.xml中,我有:

 <receiver android:name="com.example.SmsListener">

在我的BroadcastReceiver子类中我有:

public class SmsListener extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {

        // how do I reference MainActivity here?

    }
}

2 个答案:

答案 0 :(得分:0)

您无法从Context获取活动。如果你确实需要它,我想你唯一的选择是在私有静态字段中保存MainActivity的引用,然后创建一个静态的“getInstance()”方法。

public class MainActivity extends Activity {
    private static MainActivity sActivity = null;

    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sActivity = this;
        ...
    }

    public static MainActivity getInstance() {
        return sActivity;
    }
    ...
}

您可以从接收器拨打

public class SmsListener extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {

        MainActivity myMainActivity = MainActivity.getInstance();
        ...

    }
}

但是,我认为你不想这样做。

答案 1 :(得分:0)

尝试此解决方案

public class SmsListener extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {

    Intent i = new Intent (context, MainActivity.class);
    context.startActivity(i);

}
}