【问题标题】:How can you launch a service from a fragment and stop it from the same fragment?如何从一个片段启动服务并从同一个片段停止它?
【发布时间】:2021-05-08 15:27:39
【问题描述】:

我正在尝试从片段启动服务,但是在绑定意图时 startService(意图)命令不接受我,因此我测试了是否从活动启动它是否接受它,因为它需要 AppCompatActivity 功能和有自己的背景。当我在片段中尝试使用按钮启动服务时,会出现错误。

            public void onClick(View v) {
                Intent intent =new Intent(getContext(), ServiceToast.class);
                startService(intent);
            }
        });

        btnservic2.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                Intent intent =new Intent(getContext(), ServiceToast.class);
                stopService(intent);
            }
        }); ```

【问题讨论】:

    标签: android android-studio android-fragments


    【解决方案1】:

    嘿,请使用 getActivity() 而不是 getContext()

    例如(从片段调用这个)

    Intent 意图 =new Intent(getActivity(), ServiceToast.class); 启动服务(意图);

    在 Fragment 中启动您的服务使用

    getActivity().startService(new Intent(getActivity(), ServiceToast.class))

    【讨论】:

    • 无法通过该更改解析方法 'startService(android.content.Intent)。我可以启动其他活动,但不能启动服务。
    • 请查看更新后的答案。并接受它是否适合您
    • 谢谢大家。我可以用 getActivity().startService(new Intent(getContext(), ServiceToast.class)) 解决
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    相关资源
    最近更新 更多