如何从片段启动服务并从同一个片段停止服务?

How can you launch a service from a fragment and stop it from the same fragment?

我正在尝试从片段启动服务,但是在绑定意图时,startService (intent) 命令不接受我,因此我测试了我是否从 activity 启动它是否接受它因为它具有 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);
            }
        }); ```

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

例如(从片段中调用)

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

在 Fragment 中使用

启动您的服务

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