下图昨天是没被绑定的情况,右边是被绑定的情况
看下测试的效果图:
程序被关闭,服务还是会在后台运行,再次运行程序,程序还是能启动和停止服务
1、先整个类继承服务类
1 package fry; 2 3 import android.app.Service; 4 import android.content.Intent; 5 import android.os.IBinder; 6 import android.util.Log; 7 8 public class myService extends Service{ 9 10 /** 11 * 当绑定这个服务的时候调用 12 */ 13 @Override 14 public IBinder onBind(Intent arg0) { 15 Log.d("fanfan", "onBind"); 16 return null; 17 } 18 /** 19 * service被创建后调用 20 */ 21 @Override 22 public void onCreate() { 23 Log.d("fanfan", "onCreate"); 24 super.onCreate(); 25 } 26 27 /** 28 * service被start后调用 29 */ 30 @Override 31 public int onStartCommand(Intent intent, int flags, int startId) { 32 Log.d("fanfan", "onStartCommand"); 33 return super.onStartCommand(intent, flags, startId); 34 } 35 36 /** 37 * service被停止后调用 38 */ 39 @Override 40 public void onDestroy() { 41 Log.d("fanfan", "onDestroy"); 42 super.onDestroy(); 43 } 44 45 }
2、然后去配置这个服务
fry.myService是上面那个类的路径
1 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 2 package="com.example.myservice" 3 android:versionCode="1" 4 android:versionName="1.0" > 5 6 <uses-sdk 7 android:minSdkVersion="8" 8 android:targetSdkVersion="19" /> 9 10 <application 11 android:allowBackup="true" 12 android:icon="@drawable/ic_launcher" 13 android:label="@string/app_name" 14 android:theme="@style/AppTheme" > 15 <activity 16 android:name="fry.MainActivity" 17 android:label="@string/app_name" > 18 <intent-filter> 19 <action android:name="android.intent.action.MAIN" /> 20 21 <category android:name="android.intent.category.LAUNCHER" /> 22 </intent-filter> 23 </activity> 24 <activity android:name="fry.Activity01" android:exported="true"></activity> 25 26 <service android:name="fry.myService"> 27 28 </service> 29 30 </application> 31 32 </manifest>
3、再去启动和停止服务
1 package fry; 2 3 import com.example.myservice.R; 4 5 import android.app.Activity; 6 import android.content.Intent; 7 import android.os.Bundle; 8 import android.view.View; 9 10 public class Activity01 extends Activity{ 11 @Override 12 protected void onCreate(Bundle savedInstanceState) { 13 // TODO Auto-generated method stub 14 super.onCreate(savedInstanceState); 15 setContentView(R.layout.activity01); 16 } 17 18 public void onClick(View view){ 19 Intent intent=new Intent(); 20 intent.setClass(this, myService.class); 21 switch(view.getId()){ 22 case R.id.btn_start://启动服务 23 startService(intent); 24 break; 25 case R.id.btn_stop://停止服务 26 stopService(intent); 27 break; 28 } 29 } 30 }