当我的主要活动将字符串传递到广播接收器时,当应用程序当前未在屏幕上打开时,我遇到问题。从活动传递字符串到广播接收器
当创建MainActivity类时,意图过滤器通过广播接收器返回正确的信息,但只要用户转到其电话上的主屏幕,广播接收器就会在接收器被触发时开始返回“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类?
“Activity”实际上是一个UI框架。如果它不可见,那么一般来说,它没有运行。解释更多关于你想要做什么的,目前还不清楚。 – Squonk 2012-08-06 23:33:56
每次触发它时,我需要从活动传递给广播接收器的字符串,因为我构建的应用程序将根据字符串的内容执行HttpPost。 – localhost 2012-08-07 00:14:42
我还是不明白 - “活动”不应该被“事件”'触发',这就是'BroadcastReceivers'的全部要点。什么是'触发''活动' - 在我看来,你需要绕过'中间人'('活动'),因为你不能保证它会一直运行,因为你的问题显然是全部关于。 “Activity”是一个UI框架 - 它不是一个通用的类。 – Squonk 2012-08-07 00:31:09