我正在开发一个翻译应用程序,出于某些原因,我想在应用程序类中启动一些服务。我创建了一个扩展应用程序的“MyApplication”类:
public class MyApplication extends Application{
@Override
public void onCreate() {
if(PreferenceUtils.getPreferenceValue(getApplicationContext(),"clipBoardService").equals(""))
PreferenceUtils.setPreferenceValue(getApplicationContext(),"clipBoardService","True");
//Start ClipBoard Services
if(PreferenceUtils.getPreferenceValue(getApplicationContext(),"clipBoardService").equals("True"))
getApplicationContext().startService(new Intent(getApplicationContext(), ClipboardService.class));
}
你看到我用这行代码启动 ClipboardService:
getApplicationContext().startService(new Intent(getApplicationContext(), ClipboardService.class));
由于其他一些原因,我想在我的一个片段中停止此服务,称为“SettingFragment”:
public class SettingFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View inflate = inflater.inflate(R.layout.fragment_setting, container, false);
SwitchCompat scClipBoard = (SwitchCompat) inflate.findViewById(R.id.sb_ClipBoard_Service);
SwitchCompat scPopUp = (SwitchCompat) inflate.findViewById(R.id.sb_PopUp_Service);
// Turn On CheckBox's
if(PreferenceUtils.getPreferenceValue(getContext(),"clipBoardService").equals("True"))
scClipBoard.setChecked(true);
if(PreferenceUtils.getPreferenceValue(getContext(),"popUpService").equals("True"))
scPopUp.setChecked(true);
// handle OnCheckListener of CheckBox's
scClipBoard.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked == true){
PreferenceUtils.setPreferenceValue(getContext(), "clipBoardService", "True");
getActivity().getApplicationContext().startService(new Intent(getActivity().getApplicationContext(), ClipboardService.class));
}
else{
PreferenceUtils.setPreferenceValue(getContext(), "clipBoardService", "False");
getActivity().getApplicationContext().stopService(new Intent(getActivity().getApplicationContext(), ClipboardService.class));
}
}
});
你看到我用这行代码停止服务:
getActivity().getApplicationContext().stopService(new Intent(getActivity().getApplicationContext(), ClipboardService.class));
但是当我运行我的程序时,服务不会停止。我很困惑发生了什么,为什么我的服务没有停止。我在某些方面犯了错误吗?此致...