将数据从服务传递到片段

时间:2014-05-13 10:19:39

标签: android service android-fragments

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

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);
    }

然后我想在我的片段(InfoFragment)中使用这些数据(" info")

  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?

虽然它是一个片段而不是要在AndroidManifets.xml中声明的活动!!

1 个答案:

答案 0 :(得分:0)

尝试在片段中添加接收器:

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;
}
}