在我的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?
}
}
答案 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);
}
}