whirlwin..
12
CheckBox checkBox =
(CheckBox) findViewById(R.id.check_box);
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
startService(new Intent(this, TheService.class));
}
}
});
和服务:
public class TheService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy() {
Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
}
}
行startService(new Intent(this,TheClass.class)); 应该读取:startService(new Intent(this,TheService.class)).并且不要忘记将服务添加到AndroidManifest.xml (3认同)