Service:通过startService方式开启服务
来源:互联网 发布:node v4.5.0 x64.msi 编辑:程序博客网 时间:2024/05/20 13:04
1、Service的生命周期
service : 没有界面的Activity service是activity他大伯
1.第一次开启服务时会调用onCreate,onStart 方法会被调用
2.第二次第三次在开启服务,只会调用onStart方法。
3.onDestroy方法我们到设置中手动停止服务时,才会调用,服务就会被关闭
4.使用stopService方法可以关闭服务,onDestroy方法就会被执行。
注意:如果服务不stopservice会长期在后台运行
2、通过startService方式开启
1.写一个类继承Service,配置androidmanifest2.使用startService可以开启服务3.使用stopService可以停止服务
代码:
(1)在MainActivity中编写如下代码:
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } //开启服务方法 public void startService(View v){ //创建一个Intent对象,指定开启的是哪个服务 Intent intent = new Intent(this,SimpleService.class); //开启服务 startService(intent); } //关闭服务的方法 public void stopService (View vv){ //创建一个Intent对象,指定开启的是哪个服务 Intent intent = new Intent(this,SimpleService.class); //关闭服务 stopService(intent); } }
(2)新建SimpleService.java,编写如下代码:
//定义了一个服务 ,配置androidmanifestpublic class SimpleService extends Service { @Override public IBinder onBind(Intent intent) { return null; } //服务被开启调用 @Override public void onCreate() { System.out.println("生命周期中Oncreate方法调用"); super.onCreate(); } @Override public void onStart(Intent intent, int startId) { System.out.println("生命周期中onStart方法调用"); super.onStart(intent, startId); } //内部也是调用onStart方法 @Override public int onStartCommand(Intent intent, int flags, int startId) { System.out.println("生命周期中onStartCommand方法调用"); return super.onStartCommand(intent, flags, startId); } //服务被注销时调用 @Override public void onDestroy() { System.out.println("生命周期中onDestroy方法调用"); super.onDestroy(); }}
(3)在manifest.xml文件中的application节点下配置service:
<service android:name=".SimpleService"></service>
0 0
- Service:通过startService方式开启服务
- Service startService方式的服务
- Android startService开启服务
- Service:bind方式开启服务
- Android Service 服务(一)—— startService方式
- 通过startService()方法使用Service
- Service启动方式之startService
- Service启动方式之startService
- 使用startService方式启动Service
- Service混合开启笔记(startService+bindService)
- 停止通过startService()方式启动的service的两种方法
- Android Service 服务 —— startService()
- 服务(Service)全解析(一)--startService
- Service-startService启动的服务(1)
- Service服务——StartService和BindService
- Android Service 之启动服务( startService() )
- Service启动方式之startService,及注意事项
- Android中的Service(使用StartService 方式启动)
- Ulua_toLua_基本案例(八)_LuaAccessingArray
- 【VS开发】MP4与H.264
- ThinkPHP5.0执行流程分析
- 梦想科技
- Swift 初体验之二
- Service:通过startService方式开启服务
- HDU 5363 Key Set(2015 Multi-University Training Contest 6)
- 最详细的Toolbar开发实践总结
- 设计模式(五)观察者模式
- 网易美聊效果的仿照实现
- C++内存管理
- Map Set List
- 在Windows安全模式下运行MySQL的方法
- 开发者最常用的 8 款 Sublime Text 3 插件