简体   繁体   English

我的服务无法启动

[英]My service does not start

I am trying to start service in the background. 我正在尝试在后台启动服务。 When user checks the check box then it should start the service and display Toast which is in MyService class. 当用户选中复选框时,它将启动服务并显示MyService类中的Toast。 But I am not getting that Toast after starting serivce. 但是开始服务后,我没有得到那杯吐司。 What am I doing wrong in my code below? 我下面的代码在做什么错?

My main activity 我的主要活动

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));
            }
        }

    });
}
}

My service 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();
}
}

may be you are not registering your MyService Service in manifest.so register as: 可能是您没有在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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM