2012-08-06 118 views
0

当我的主要活动将字符串传递到广播接收器时,当应用程序当前未在屏幕上打开时,我遇到问题。从活动传递字符串到广播接收器

当创建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类?

+0

“Activity”实际上是一个UI框架。如果它不可见,那么一般来说,它没有运行。解释更多关于你想要做什么的,目前还不清楚。 – Squonk 2012-08-06 23:33:56

+0

每次触发它时,我需要从活动传递给广播接收器的字符串,因为我构建的应用程序将根据字符串的内容执行HttpPost。 – localhost 2012-08-07 00:14:42

+0

我还是不明白 - “活动”不应该被“事件”'触发',这就是'BroadcastReceivers'的全部要点。什么是'触发''活动' - 在我看来,你需要绕过'中间人'('活动'),因为你不能保证它会一直运行,因为你的问题显然是全部关于。 “Activity”是一个UI框架 - 它不是一个通用的类。 – Squonk 2012-08-07 00:31:09

回答

0

我在这里可能是错误的,但从逻辑上讲,当接收器被触发时,“广播接收器开始返回”null的原因是因为当传递给onReceive构造函数的上下文在用户转到主屏幕。

我想一个传递字符串的解决方案是在MainActivity中创建一个公共静态字符串变量,用于存储要传递的字符串值。然后你所要做的就是在你的BroadcastReceiver中静态地访问这个字符串。

+0

**“...在MainActivity中创建一个公共静态字符串变量......”**请不要为Android的“活动”提供此建议。任何延伸'Activity'的类都不应暴露静态变量或方法。 – Squonk 2012-08-06 23:36:59

+0

这是否有任何解决方法? – localhost 2012-08-07 00:15:53

+0

@Squonk哦,我不知道!我很好奇,为什么我们不应该那样做? – 2012-08-07 01:40:30