Android Service的简单用法,IntentService和Service的区别

小白第一次写,不足之处还望指正。

作为安卓四大组件的Service,常见的使用方式有两种:

1、startService()  

    注意点:<1>调用方法顺序为onCreate()->onStartCommand()->onStop()->onDestroy()

                 <2>在执行了startService()后,再次点击startService(),不会再执行onCreate(),只执行onStartCommand()

                 <3>如果程序没有执行stopService(),Service将在永久在后台运行 ,所以记得要stopService

 2、bindService()

      注意点:<1>调用方法顺序onCreate()->onBind()[包含自定义的方法]->onUnbind()->onDestroy()

                    <2>如果没有执行unBind(),Service将在永久在后台运行 ,所以记得要unBind

                   

IntentService和Service的区别?

        Service执行完不会自动调用destroy(),IntentService执行完会自动调用destroy()


例子:此例简单使用ButterKnife获取组件,可以直接用findViewById()方法获取

MainActivity

package com.example.yzh.servicetest;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {
    private MyService.DownloadBinder binder;

    @BindView(R.id.start_service)
    Button startService;
    @BindView(R.id.stop_sercice)
    Button stopSercice;
    @BindView(R.id.bind_service)
    Button bindService;
    @BindView(R.id.unbind_service)
    Button unbindService;
    @BindView(R.id.start_intent_service)
    Button startIntentService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.start_service, R.id.stop_sercice, R.id.bind_service, R.id.unbind_service, R.id.start_intent_service})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.start_service:
                Intent startIntent = new Intent(MainActivity.this, MyService.class);
                startService(startIntent);
                break;
            case R.id.stop_sercice:
                Intent stopIntent = new Intent(MainActivity.this, MyService.class);
                stopService(stopIntent);
                break;
            case R.id.bind_service:
                Intent bindIntent = new Intent(MainActivity.this, MyService.class);
                bindService(bindIntent, connection, BIND_AUTO_CREATE);
                break;
            case R.id.unbind_service:
                unbindService(connection);
                break;
            case R.id.start_intent_service:
                Intent start_Intent = new Intent(MainActivity.this, MyIntentService.class);
                startService(start_Intent);
                break;
        }
    }

    //在bindService时,连接的两种状态
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //接受返回的IBinder对象,并调用其中的方法
            binder = (MyService.DownloadBinder) service;
            binder.startDownload();
            binder.getProgress();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            binder = null;
        }
    };

}

MyService.java

package com.example.yzh.servicetest;

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


public class MyService extends Service {
    private static String TAG="MyService";
    private DownloadBinder downloadBinder = new DownloadBinder();

    @Override
    public void onCreate() {
        Toast.makeText(this,"onCreate",Toast.LENGTH_SHORT).show();
        Log.e(TAG,"onCreate");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this,"onStartCommand",Toast.LENGTH_SHORT).show();
        Log.e(TAG,"onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        Toast.makeText(this,"onBind",Toast.LENGTH_SHORT).show();
        Log.e(TAG,"onBind");
        //返回IBinder对象
        return downloadBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Toast.makeText(this,"onUnbind",Toast.LENGTH_SHORT).show();
        Log.e(TAG,"onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this,"onDestroy",Toast.LENGTH_SHORT).show();
        Log.e(TAG,"onDestroy");
        super.onDestroy();
    }

    //定义binder
    class DownloadBinder extends Binder {
        public void startDownload(){
            Log.e(TAG,"startDownload");
        }

        public int getProgress(){
            Log.e(TAG,"getProgress");
            return 0;
        }
    }
}

MyIntentService.java

package com.example.yzh.servicetest;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;


public class MyIntentService extends IntentService {

    public MyIntentService() {
        super("MyIntentService");
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this,"onDestroy",Toast.LENGTH_SHORT).show();
        Log.e("MyIntentService","onDestroy");
        super.onDestroy();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Toast.makeText(this,"onHandleIntent",Toast.LENGTH_SHORT).show();
        Log.e("MyIntentService","onHandleIntent");
    }

}


activity_main.xml

<?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:orientation="vertical"
    android:layout_height="match_parent"
    tools:context="com.example.yzh.servicetest.MainActivity">

    <Button
        android:id="@+id/start_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="start_service"/>

    <Button
        android:id="@+id/stop_sercice"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="stop_sercice"/>

    <Button
        android:id="@+id/bind_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="bind_service"/>

    <Button
        android:id="@+id/unbind_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="unbind_service"/>

    <Button
        android:id="@+id/start_intent_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="start_intent_service"/>

</LinearLayout>

在AndroidMenifest.xml中加上

<service android:name=".MyIntentService"></service>
<service android:name=".MyService"></service>




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值