我正在尝试在后台启动服务。当用户选中复选框时,它应该启动服务并显示 MyService 类中的 Toast。但是在开始服务后我没有得到那个吐司。我在下面的代码中做错了什么?
我的主要活动
public class SampleServiceActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final CheckBox cb = (CheckBox) findViewById(R.id.checkBox1);
cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked) {
Toast.makeText(getBaseContext(), "Checked", Toast.LENGTH_LONG).show();
startService(new Intent(getBaseContext(), MyService.class));
} else {
Toast.makeText(getBaseContext(), "Unchecked", Toast.LENGTH_LONG).show();
stopService(new Intent(getBaseContext(), MyService.class));
}
}
});
}
}
我的服务等级
public class MyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
//method to stop service
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
}