2012-05-20 83 views
0

我想在後臺啓動服務。當用戶選中複選框時,它應該啓動該服務並顯示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(); 
} 
} 
+3

你確定在清單中註冊您的MyService? –

+0

好問題伊姆蘭。我沒有在那裏註冊。 – 2619

+0

然後在清單中註冊 –

回答

1

可能是你沒有註冊您的MyService服務manifest.so寄存器爲:

<?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> 
+0

如果它的工作,然後接受爲其他人的答案help.thanks –