从一个片段广播的意图到服务 [英] Broadcasting an intent from a fragment to a service

查看:145
本文介绍了从一个片段广播的意图到服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个活动,当我发送的意图,一个服务,我只是使用 sendBroadcast ,但我不能从一个片段做同样的,因为一个片段必须是静态的类。什么是处理这个问题的最好方法?

我已经考虑具有接收的上下文的方法,但是这不会在一个片段的情况下工作。

目前我的code是

 公共静态类ExampleSectionFragment扩展片段{
    公共静态最后弦乐ARG_SECTION_NUMBER =SECTION_NUMBER;    @覆盖
    公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,
            捆绑savedInstanceState){
        查看rootView = inflater.inflate(R.layout.fragment_section_example,集装箱,FALSE);
        捆绑ARGS = getArguments();        //例意图广播按钮preSS服务
        rootView.findViewById(R.id.action_start)
                .setOnClickListener(新View.OnClickListener(){
                    @覆盖
                    公共无效的onClick(查看视图){
                        意向意图=新意图(RECORDING_INTENT);
                         sendBroadcast(意向);
                    }
                });
        返回rootView;
    }
}

sendBroadcast返回错误在eclipse:


  

无法进行静态引用从类型ContextWrapper

非静态方法sendBroadcast(意向)

解决方案

片段 s的连接到活动 ,这是一个子类上下文 - 更换你的 sendBroadcast 调用(这是试图使用外部类' sendBroadcast )使用 getActivity()sendBroadcast - 这将使用上下文活动的片段正在连接到

In an activity, when I send an intent to a service I just use sendBroadcast, but I cannot do the same from a fragment because a fragment has to be a static class. What is the best way of dealing with this?

I have considered having a method that receives a context, but this wouldn't work in the case of a fragment.

Currently my code is

public static class ExampleSectionFragment extends Fragment {
    public static final String ARG_SECTION_NUMBER = "section_number";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_section_example, container, false);
        Bundle args = getArguments();

        //Example intent to broadcast to service on button press
        rootView.findViewById(R.id.action_start)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(RECORDING_INTENT);
                         sendBroadcast(intent);
                    }
                });
        return rootView;
    }
}

sendBroadcast returns the error in eclipse:

Cannot make a static reference to the non-static method sendBroadcast(Intent) from the type ContextWrapper

解决方案

Fragments are attached to an Activity, which is a subclass of Context - replace your sendBroadcast call (which is attempting to use the outer class' sendBroadcast) with getActivity().sendBroadcast - this will use the Context associated with Activity the Fragment is currently attached to.

这篇关于从一个片段广播的意图到服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆