简体   繁体   English

android:通过广播接收器将某些内容传回活动

[英]android: passing something back to activity from a broadcast reciever

so i have this problem where i have something to pass back to the activity, but the problem is i don't know how, i've read some threads but its a bit cloudy and confusing, can anyone of your shed some light about this. 所以我有这个问题,我有一些东西要传回活动,但问题是我不知道如何,我已经阅读了一些线程,但它有点混乱和混乱,你能否有人对此有所了解。 i just want to pass something back to the activity from my reciever (BroadcastReciever). 我只是想从我的接收器(BroadcastReciever)传回一些东西。 I have read a thread that you can start an activity but the problem is that there is a bit of a confusion if passing an extra on your intent to an activity is allowed?. 我已经阅读了一个线程,你可以开始一个活动,但问题是,如果允许将一个额外的意图传递给一个活动,会有一点混乱吗? Thanks for any inputs any of you could provide. 感谢您提供的任何输入。

Possible duplicate answer https://stackoverflow.com/a/6857648/760489 可能的重复答案https://stackoverflow.com/a/6857648/760489

you can do this way by setting flag in intent when you start the activity from broadcast receiver 当您从广播接收器启动活动时,可以通过设置意图中的标记来执行此操作

public void onReceive(Context context, Intent intent){
    Intent i = new Intent(context, DestinationActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    i.putExtra("PATH", path);
    context.startActivity(i);
}

The FLAG_ACTIVITY_SINGLE_TOP makes sure the apps doesn't re-open if already open. FLAG_ACTIVITY_SINGLE_TOP可确保应用程序在已打开时不会重新打开。 This means that the "old" intent that opened YourActivity in the first place is re-used and it will NOT contain the extra values. 这意味着首先打开YourActivity的“旧”意图将被重用,并且不会包含额外的值。 You have to catch them in another method called onNewIntent() in YourActivity. 您必须在YourActivity中另一个名为onNewIntent()的方法中捕获它们。

Check out the complete answer from top link 查看顶部链接的完整答案

Try this out: 试试这个:

public void onReceive(Context context, Intent intent)
{

    Intent i = new Intent(context, DestinationActivity.class);
    i.putExtra("PATH", path);
    context.startActivity(i);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM