从一个片段广播的意图到服务 [英] Broadcasting an intent from a fragment to a service
问题描述
在一个活动,当我发送的意图,一个服务,我只是使用 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
解决方案
Fragment
s are attached to anActivity
, which is a subclass ofContext
- replace yoursendBroadcast
call (which is attempting to use the outer class'sendBroadcast
) withgetActivity().sendBroadcast
- this will use theContext
associated withActivity
theFragment
is currently attached to.这篇关于从一个片段广播的意图到服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!