为什么我不能停止服务?

时间:2013-08-12 01:12:27

标签: android service android-notifications android-checkbox checkboxpreference

我无法通过checkboxpreference停止我的服务。这是CheckBoxPreference代码

CheckBoxPreference checkBoxPref = (CheckBoxPreference) getPreferenceManager().findPreference("firstDependent");
        checkBoxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {            
              public boolean onPreferenceChange(Preference preference, Object newValue) {
                  if (newValue.toString().equals("true")) {
                      editor.putBoolean("notification_a", true);
                      editor.commit(); 
                      //sendSimpleNotification();
                      startService(new Intent(settings.this,service.class));
                      Log.d("Check", "startService from checkbox");

                  }
                  else if (newValue.toString().equals("false")){
                      editor.putBoolean("notification_a", false);
                      editor.commit(); 
                     //mNotificationManager.cancel(SIMPLE_NOTIFICATION_ID); 
                      stopService(new Intent(getApplicationContext(),service.class)); 
                      Log.d("Check", "stopService from checkbox"); 
                  }
                  return true;
              }
        });

因此,如果未选中该复选框,则服务将停止,但不会发生任何事情。为什么呢?

1 个答案:

答案 0 :(得分:1)

public class YOUR_CLASS extends Activity implements View.OnClickListener{

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pianostudio);
...CODE...   
    CheckBox checkBoxPref = (CheckBox)findViewById(R.id.YOUR_CHECKBOX_ID); 
    checkBoxPref.setOnClickListener(this);
...OTHER CODE...
}


@Override
public void onClick(View v) {
    switch(v.getId()){
        case R.id.YOUR_ID_CHECKBOX:{       //checkbox per de/selezionare l'idoneita' di un esame
            if (checkBoxPref.isChecked()){
                editor.putBoolean("notification_a", true);
                editor.commit(); 
                //sendSimpleNotification();
                startService(new Intent(settings.this,service.class));
                Log.d("Check", "startService from checkbox");;
            }
            else{
                editor.putBoolean("notification_a", false);
                editor.commit(); 
                //mNotificationManager.cancel(SIMPLE_NOTIFICATION_ID); 
                stopService(new Intent(getApplicationContext(),service.class)); 
                Log.d("Check", "stopService from checkbox"); 
            }
            break;
         }
     }
}
}
相关问题