当应用程序当前未在屏幕上打开时,我在将字符串从主要活动传递到广播接收器时遇到问题。
创建 MainActivity 类时,intent 过滤器通过广播接收器返回正确的信息,但是一旦用户进入手机的主屏幕,当接收器在屏幕外触发时,广播接收器就会开始为 toast 返回“null”。
1.新意图
Intent home_page = new Intent(newIntent.this,MainActivity.class);
ownAddress = ""+customInput.getText().toString();
home_page.putExtra("session_number", ""+ownAddress);
startActivity(home_page);
2. MainActivity.java:
public class MainActivity extends DroidGap {
SmsReceiver mAppReceiver = new SmsReceiver();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
final String ownAddress = bundle.getString("session_number");
registerReceiver(mAppReceiver, new IntentFilter("SmsReceiver"));
Intent intent = new Intent("SmsReceiver");
intent.putExtra("passAddress", ownAddress);
sendBroadcast(intent);
}
}
3.SmsReceiver.java:
public class SmsReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Toast showme = Toast.makeText(context,"Number: "+intent.getExtras().get("passAddress"),Toast.LENGTH_LONG);
showme.show();
}
}
当应用程序仅在后台运行或无论何时创建 MainActivity 类时,是否有将字符串传递给广播接收器?