Service 定义(startService、bindService、IntentService)

Service:

是Android中实现程序后台运行的解决方案。
定义为服务
Service默认并不会运行在子线程中,它也不会运行在一个独立的进程中,它同样执行在UI线程中,因此,不要在Service中执行耗时的操作,如果需要执行耗时的操作,可以在Service中创建子线程来完成耗时操作。

什么是手机病毒?

手机病毒是编制者在手机程序中插入带破坏数据。吸费。监控等功能的代码,能影响手机使用,能自我复制的一组指令或者程序代码。
病毒的共性是拥有潜伏性,触发性,传染性,破坏性。
病毒都是偷偷的在后台执行预设的功能。

为什么要用Service?

大部分病毒利用Service的特点,可以不知不觉(后台)完成预设的功能。
作为Android工程师,至少需要了解Service是如何在后台完成预设功能。
在真实的商业项目中都有定期在后台执行任务(如:下载,上传等)的需求。
当某个功能需要执行很长时间(如:下载,收集数据等),并且在执行过程中不需要让用户操作,不需要Activity进行交互的情况下,可以通过Service在后台完成指定任务。

Service有几种启动模式?
有两种启动模式:

startService()启动方式:主要用于执行后台计算
bindService()启动方式:主要用于和其它组件的交互

startService的特点及优缺点?

Service会经历 onCreate –> onStart stopService的时候直接onDestroy
如果是 调用者直接退出而没有调用stopService的话,Service会一直在后台运行。 下次调用者再起来仍然可以stopService。

bindService 的特点及优缺点?

Service只会运行onCreate, 这个时候 调用者和Service绑定在一起

调用者退出了,Srevice就会调用onUnbind–>onDestroyed 所谓绑定在一起就共存亡了。

两者放在一块的代码演示:

package com.example.myapplication15;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button btn_start;
private Button btn_end;
private Button bind;
private Button unbind;
private Button main;

    private MyService.DownloadBinder downloadBinder;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            downloadBinder = (MyService.DownloadBinder) iBinder;
            downloadBinder.startDownload();
            downloadBinder.getProgress();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };




    DownLoadBinder downLoadBinder=new DownLoadBinder();


    public class DownLoadBinder extends Binder{
       public void startDownload(){}


   }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_start=findViewById(R.id.btn_start);
        btn_end=findViewById(R.id.btn_end);
        btn_start.setOnClickListener(this);
        btn_end.setOnClickListener(this);
        bind = findViewById(R.id.main_bind);
        unbind = findViewById(R.id.main_unbind);
        bind.setOnClickListener(this);
        unbind.setOnClickListener(this);
        main=findViewById(R.id.main2_btn);
        main.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
      switch (view.getId()){
          case R.id.main_bind:
              Intent bindIntent = new Intent(this, MyService.class);
              bindService(bindIntent, connection, BIND_AUTO_CREATE);
              break;
          case R.id.main_unbind:
              unbindService(connection);
              break;
          case  R.id.btn_start:
              Intent statintent=new Intent(MainActivity.this,MyService.class);
             startService(statintent);
              break;
          case R.id.btn_end:
              Intent endintent=new Intent(MainActivity.this,MyService.class);
              stopService(endintent);
              break;
          case  R.id.main2_btn:
              Intent intent=new Intent(MainActivity.this,Main2Activity.class);
              startActivity(intent);
          default:
              break;
      }
    }
}

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.myapplication15.MainActivity">

    <Button
        android:text="开始"
        android:layout_marginTop="50dp"
        android:id="@+id/btn_start"
        android:layout_gravity="center"
        android:layout_width="80dp"
        android:layout_height="50dp" />
    <Button
        android:text="结束"
        android:layout_marginTop="50dp"
        android:id="@+id/btn_end"
        android:layout_gravity="center"
        android:layout_width="80dp"
        android:layout_height="50dp" />
    <Button
        android:id="@+id/main_bind"
        android:text="绑定"
        android:layout_marginTop="50dp"
        android:layout_gravity="center"
        android:layout_width="80dp"
        android:layout_height="50dp" />
    <Button
        android:id="@+id/main_unbind"
        android:text="解绑"
        android:layout_marginTop="50dp"
        android:layout_gravity="center"
        android:layout_width="80dp"
        android:layout_height="50dp" />
    <Button
        android:id="@+id/main2_btn"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="转到main2"/>
</LinearLayout>

写一个类继承service:

package com.example.myapplication15;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import static android.content.ContentValues.TAG;

public class MyService extends Service {
    private DownloadBinder mBinder=new DownloadBinder();

    class  DownloadBinder extends Binder {
        public  void startDownload(){
            Log.e(TAG, "MyService: "+"startDownload ");
        }
        public  int getProgress(){
            Log.e(TAG, "MyService: "+"getProgress ");
            return  0;
        }
    }

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.

        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("Myservice", "onCreate: executed" );

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("Myservice", "onStartCommand: executed" );
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0;i<10;i++){
                    Log.e("Service"+ Thread.currentThread().getName(),i+"***" );

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("Myservice"+Thread.currentThread().getName() ,"onDestroy: executed" );
    }
}

当点击开始的时候 log出如图的效果:
这里写图片描述

当点击结束的时候:
这里写图片描述
当再次连续点击开始时,oncreate 只是被执行了一次。而onStartCommand可以被执行很多次:
这里写图片描述
当点击绑定的时候:
这里写图片描述

当点击解绑的时候 执行销毁:
这里写图片描述

IntentService的特点及其优缺点?

1是一种服务,比较适合高优先级的后台任务
2.任务结束自动退出
3.IntentService是Service的子类,用来处理异步请求,IntentService在onCreate()通过HandlerThread开启一个线程

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值