gpt4 book ai didi

android - 将数据从服务传递到 fragment

转载 作者:太空狗 更新时间:2023-10-29 15:04:01 26 4
gpt4 key购买 nike

我想将数据从服务传递到 fragment 。这是我在服务中的代码

public void putInfo(){
Intent trIntent = new Intent("android.intent.action.MAIN");
trIntent.setClass(this,WelcomeActivity.class);
trIntent.putExtra("info", strengthAmplitude+"");
trIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(trIntent);
}

然后我想像那样在我的 fragment (InfoFragment) 中使用此数据(“信息”)

  String msg =  getActivity().getIntent().getExtras().getString("info");

我遇到错误。

E/AndroidRuntime(25036): java.lang.RuntimeException: Unable to start service 
com.BackupAndTools.service.InfoService@41e6b498 with Intent {
cmp=com.BackupAndTools/.service.InfoService }:
android.content.ActivityNotFoundException: Unable to find explicit activity class
{com.BackupAndTools/com.BackupAndTools.views.InfoFragment}; have you declared this
activity in your AndroidManifest.xml?

虽然它是一个 fragment 而不是要在 AndroidManifets.xml 中声明的 Activity !!

最佳答案

尝试在 fragment 中添加接收器:

class CustomReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
String data= intent.getExtra(DATA);
}
}

现在在您的 Fragment 中使用 Intent 过滤器注册接收器:

@Override
public void onStart() {
super.onStart();
receiver = new CustomReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(MY_TRIGGER);
getActivity().registerReceiver(receiver, filter);
}

现在在您的服务中:

public class NumberThoery extends Service {


public static String MY_TRIGGER = "trigger";

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
intent.putExtra(DATA,"test");
sendBroadcast(intent,MY_TRIGGER);
return START_STICKY;
}



@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}

关于android - 将数据从服务传递到 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23628553/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com