您的位置:首页 > 移动开发 > Android开发

Android:Service非绑定

2013-10-18 14:15 302 查看
Service

非绑定的Service:不与Activity同生命周期的Service

第一步

在AndroidManifest.xml文件中进行配置

<service
android:name="com.xxx.XxxService"
android:enabled="true" >
</service>


第二步

service类编写

class XxxService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onCreate() {
super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}

@Override
public void onDestroy() {
super.onDestroy();
}
}

想要进行的操作编写在onStartCommand方法里就可以了

第三步

Service的调用

Intent intent = new Intent(XxxActiviy.this,XxxService.class);
startService(intent);


第四步

Service的停止

Intent intent = new Intent(XxxActiviy.this,XxxService.class);
stopService(intent);


注意:

如果在Service的onStartCommand方法中开启了线程,那么需要在onDestroy方法中把线程关闭,才能在结束Service的时候一起结束线程,否则Service停止,线程却不会停止
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: