您好我正在尝试运行一个具有一个活动的代码和一个在新消息到来时运行的BroadcastReceiver,是的,它运行得很清楚但是我遇到了BroadcastReceiver对象的问题!
它是MainActivity CLASS的一部分:
public class MainActivity extends FragmentActivity {
private IncomingSms checkAndDo; //=> OBJECT
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkAndDo= new IncomingSms();
checkAndDo.setProgramState(210); // program state is a variable
checkAndDo.getProgramState(this); // Toast output : " >>>210 "
....
但是当一条新消息出现并且onReceived()被调用时,问题就开始了! IncommingSms类:
公共类IncomingSms扩展了BroadcastReceiver {
private int programState=110; // Which state we are ? 110=> white / 111=> off / 210=>black ...
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
this.getProgramState(context);
// This method called again but toast output is : ">>>110"
// which is initial value !?
AND ....
}
public void setProgramState(int status) {
this.programState=status;
}
public void getProgramState( Context context) {
Toast.makeText(context, ">>>"+this.programState , Toast.LENGTH_LONG).show();
}
问题:我不确定为什么会发生这种情况,但onReceive()仅使用非常糟糕的初始值。有什么想法吗?
答案 0 :(得分:1)
this.getProgramState(context); // This method called again but toast output is : ">>>110" // which is initial value !?
您遇到了这个问题,因为您在清单中注册了BroadcastReceiver。因此Android将创建一个新的BroadcastReceiver并将sms广播传递给它。
如果您想获得您在程序中设置的状态,则必须在Activity中注册BroadcastReceiver。
IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(checkAndDo, filter);