Android Service使用

简介:

Android开发中,当需要创建在后台运行的程序的时,就要用到Service。

Service跟Activities是不同的(可以理解为后台与前台的区别),

启动Service过程如下:

context.startService()  ->onCreate()- >onStart()->Service running

其中onCreate()可以进行一些服务的初始化工作.

停止Service过程如下:

context.stopService() | ->onDestroy() ->Service stop

示例:

 

public  class  myservice extends  Service {
 
     @Override
     public  IBinder onBind(Intent intent) {
         // TODO Auto-generated method stub
         return  null ;
     }
     
     @Override
     public  void  onCreate(){
         Toast.makeText( this , "My Service Create" , Toast.LENGTH_SHORT).show();
     }
     
     @Override
     public  void  onDestroy(){
          Toast.makeText( this , "My Service Destroy" , Toast.LENGTH_SHORT).show();
     }
     
     @Override
     public  void  onStart(Intent intent, int  startId)
     {
          Toast.makeText( this , "My Service Started" , Toast.LENGTH_SHORT).show();
 
     }
 
}

 

 调用:

@Override
public  void  onClick(View v) {
     // TODO Auto-generated method stub
     switch  (v.getId()) {
     case  R.id.StartSevice:
         startService( new  Intent( this , myservice. class ));
         break ;
     case  R.id.StopService:
         stopService( new  Intent( this , myservice. class ));
         break ;
     }
}

 调用startService方法时,执行myservice中的onCreate方法和onDestroy方法。

 调用stopService方法时,执行onDestroy方法。

 

Android服务总结

Android服务使用

Android中Service的使用详解和注意点(LocalService)

Android 使用AIDL调用外部服务 (RemoteService)


本文转自Work Hard Work Smart博客园博客,原文链接:http://www.cnblogs.com/linlf03/archive/2013/06/14/3135273.html,如需转载请自行联系原作者

目录
相关文章
|
5天前
|
Android开发
Android 11 添加Service服务SELinux问题
Android 11 添加Service服务SELinux问题
48 1
|
5天前
|
Android开发
Android基础知识:请解释Service是什么,它与IntentService的区别是什么?
Android基础知识:请解释Service是什么,它与IntentService的区别是什么?
44 0
|
5天前
|
XML Java Android开发
Android Studio App开发之服务Service的讲解及实战(包括启动和停止,绑定与解绑,推送服务到前台实现音乐播放器,附源码)
Android Studio App开发之服务Service的讲解及实战(包括启动和停止,绑定与解绑,推送服务到前台实现音乐播放器,附源码)
207 0
|
5天前
|
Android开发
Android Service Call /dev/xxx SELinux
Android Service Call /dev/xxx SELinux
17 1
|
4天前
|
存储 监控 Java
Android Service之设备存储空间监控 DeviceStorageMonitorService
Android Service之设备存储空间监控 DeviceStorageMonitorService
18 2
|
5天前
|
Android开发 数据库管理
Android如何在Activity和Service之间传递数据
Android如何在Activity和Service之间传递数据
12 3
|
5天前
|
Android开发
Android Service的两种使用方法
Android Service的两种使用方法
16 2
|
5天前
|
数据可视化 Android开发
[Android 四大组件] --- Service
[Android 四大组件] --- Service
24 0
|
5天前
|
Android开发 Kotlin
android开发,使用kotlin学习Service
android开发,使用kotlin学习Service
69 1
|
9月前
|
Android开发
Android手写占位式插件化框架之Activity通信、Service通信和BroadcastReceiver通信(二)
Android手写占位式插件化框架之Activity通信、Service通信和BroadcastReceiver通信
81 0