Java 我的服务不启动
我正在尝试在后台启动服务。当用户选中该复选框时,它应该启动服务并显示MyService类中的Toast。但我不会在开始赛后得到祝酒词。我在下面的代码中做错了什么 我的主要活动Java 我的服务不启动,java,android,android-service,Java,Android,Android Service,我正在尝试在后台启动服务。当用户选中该复选框时,它应该启动服务并显示MyService类中的Toast。但我不会在开始赛后得到祝酒词。我在下面的代码中做错了什么 我的主要活动 public class SampleServiceActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState)
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();
}
}
可能您没有在清单中注册MyService服务。请注册为:
<?xml version="1.0" encoding="utf-8" ?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xxx.xxx" android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/xxx" android:label="@string/app_name" >
<activity> ... </activity>
<service android:name=".MyService " />
</application>
</manifest>
...
您确定要在清单中注册您的MyService吗?问得好,伊姆兰。我没有在那里注册。