我的服务没有启动

时间:2012-05-20 06:43:59

标签: java android android-service

我正在尝试在后台启动服务。当用户选中复选框时,它应该启动服务并显示MyService类中的Toast。但是在开始服用后我没有得到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();
}
}

1 个答案:

答案 0 :(得分:1)

您可能没有在manifest.so注册中注册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>