Service的生命周期
2017-07-16 15:02
120 查看
Service的生命周期
Service的生命周期例如以下
第一种:Call to startService()方法->onCreate()->onStartCommand()->service running-
>onDestory->service shut down)
案例:
第一步
在布局文件加入两个button
第三步配置文件在<application>节点下增加子节点(与activity节点平级):
<service android:name="com.example.simpleservice.SimpleService" >
</service>
第四步在MainActivity中增加button点击方法:
Service的生命周期例如以下
第一种:Call to startService()方法->onCreate()->onStartCommand()->service running-
>onDestory->service shut down)
案例:
第一步
在布局文件加入两个button
<Button android:id="@+id/start_service" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="32dp" android:onClick="dostartService" android:text="启动simpleService" /> <Button android:id="@+id/stop_service" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/start_service" android:layout_marginTop="51dp" android:onClick="dostopService" android:text="停止simpleService" />第二步创建SimpleService类继承Service
package com.example.simpleservice; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class SimpleService extends Service{ private String tag ="simpleService"; @Override public void onCreate() { Log.d(tag, "simpleserviece ->onCreate()"); super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(tag, "simpleserviece ->onStartCommand"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { Log.d(tag, "simpleserviece ->onDestroy()"); super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return null; } }
第三步配置文件在<application>节点下增加子节点(与activity节点平级):
<service android:name="com.example.simpleservice.SimpleService" >
</service>
第四步在MainActivity中增加button点击方法:
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void dostartService(View v){ Intent intent = new Intent(this, SimpleService.class); startService(intent); } public void dostopService(View v){ Intent intent = new Intent(this, SimpleService.class); stopService(intent); } }
相关文章推荐
- Android-Service的生命周期
- Android Service的生命周期2
- Android程序开发入门——组件生命周期之Service
- service的生命周期
- 四大组件---Service的生命周期(一)
- Android开发笔记(四十一)Service的生命周期
- android service后台服务生命周期与常驻后台
- Service的两种启动方式和对应的生命周期
- java-Service生命周期及用法! - 随心
- Service的生命周期
- 40-Service学习第一发Service的生命周期
- Android(java)学习笔记171:Service生命周期
- Android服务Service详解(作用,生命周期,AIDL)系列文章--服务的生命周期
- android service 生命周期
- Android Activity、Service、BroadcastReceiver 的生命周期
- WCF技术剖析之二十三:服务实例(Service Instance)生命周期如何控制[下篇]
- android service 生命周期及场景
- service生命周期及使用
- Android Service的生命周期2
- Android:Service的非绑定式的创建和生命周期