Android Service: 启动service, 停止service

[ 启动service ][ 停止Service ]

目录

1.1 定义Service类

2. 在AndroidManifest.xml文件中注册Service

3. 在Activity中启动Service

4. 停止Service



1.1 定义Service类

@Override
public IBinder onBind(Intent intent) 

  是继承Service类一定要包含的函数。

 1.2 然后我们通过Override三个函数来学期Serivce的启动,如下:

public void onCreate()
public int onStartCommand(Intent intent, int flags, int startId)
public void onDestroy()
public void onCreate()

  onCreate() 是在Service第一次启动时会调用的函数。当Service已经在运行时,再次startService()并不会调用onCreate()函数。

public int onStartCommand(Intent intent, int flags, int startId)

  onStartCommand() 是每次启动Service都会调用的函数。即使Service已经启动了,再次startService()还是会调用onStartCommand()函数。

public void onDestroy()

  onDestroy() 是停止Service时所调用的函数。在activity中调用stopService()停止函数,会调用这个onDestroy()函数。

 1.3 Service 类定义定义如下:

public class MyService extends Service {  
  
    public static final String TAG = "MyService";  
  
    @Override  
    public void onCreate() {  
        super.onCreate();  
        Log.d(TAG, "onCreate() executed");  
    }  
  
    @Override  
    public int onStartCommand(Intent intent, int flags, int startId) {  
        Log.d(TAG, "onStartCommand() executed");  
        return super.onStartCommand(intent, flags, startId);  
    }  
      
    @Override  
    public void onDestroy() {  
        super.onDestroy();  
        Log.d(TAG, "onDestroy() executed");  
    }  
  
    @Override  
    public IBinder onBind(Intent intent) {  
        return null;  
    }  
  
} 

2. 在AndroidManifest.xml文件中注册Service

  在<application>中嵌套:

<service android:name="package_name.class_name"> 
</service>

3. 在Activity中启动Service

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

  第一次启动Service, 会调用onCreate(), onStartCommand()。之后几次启动Service, 只会调用onStartCommand()。并且Service会一直在后台运行

4. 停止Service

  在Activity中停止Service

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

  在停止Service后,再启动Service,则又会调用onCreate(),onStartCommand()。
————————————————

原文链接:https://blog.csdn.net/mozart_cai/article/details/25913889

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值