《第一行代码》第二版 学习总结27 关于服务的一些基本知识

      最近利用下班时间,找了看什么书比较适合初学android的朋友,很多人推荐了《第一行代码》这本书,于是就买了一本,感觉看书,思考,动手,再思考和总结这样过程还是很有必要的,于是就打算把自己学习的东西简单的总结一下;方便自己以后查找,也有利于学习的巩固。在这里首先要感谢一下书籍的作者——郭霖前辈。

      其实关于服务我也介绍过两个零散的知识点一个是前台服务,一个IntentService;如果之前没有学习过的,可以简单了解一下,其实本部分内容应该放在服务这一块的最前面的;因为在本篇我们主要介绍一下服务的两种启动方式以及服务的生命周期,还有使用时候的一些注意事项;我主要会以列表的形式给出需要注意的点,至于如何实现以及验证,一方面我在代码中有所体现,一方面还需要自己多加动手尝试。本文示例代码链接

1,关于服务的一些基本概念和使用注意事项

关于服务,其实其应用是非常广泛的,可以简单了解成美元界面的活动,说明其主要的职能是在后台执行一些逻辑业务。而且,还可以实现跨应用的功能调用(AIDL的方式,可以参见我另一篇博客介绍的比较详细)

下面就来简单的列举一下学习服务的几个要点:

  • 服务的两种开启方式(startService()和bindService()的使用)
  • 服务的生命周期(包括服务生命周期方法在什么时候调用)
  • 如何调用服务里面的私有方法(比如支付宝通过AIDL开发一个支付接口给其他程序调用,当然,这是跨应用了,如果在本应用中又该如何实现了,方式是很多的)
  • 服务关闭的方式有哪几种(通过调用stopService(),unBindService(),还有一个stopSelf()方法哟)只是它们使用的方式不一样,正因为方式,位置等不一样,才用利于不同的功能需求的实现。

2,示例代码

因为这一部分都是较基础的知识,理解不难,主要是能够看完病动手做了实践,下面就给出具体示例代码(其实我完全用一个服务就可以了,但是为了演示的更清晰,特地写了三个服务来演示)

MainActivity.java代码:

package com.hfut.operationservicelifespace;

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

public class MainActivity extends AppCompatActivity {

    MyServiceConnection connection = new MyServiceConnection();
    ServiceConnection serviceConnection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    private static final String TAG = "MainActivity";

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

    }


    public void mStartService(View view) {
        Intent intent = new Intent(this, ServiceForStart.class);
        for (int i = 0; i < 5; i++) {
            startService(intent);
        }
        Log.i(TAG, "mStartService: ");
    }

    public void mStopService(View view) {

        Intent intent = new Intent(this, ServiceForStart.class);
        stopService(intent);
        Log.i(TAG, "mStopService: ");
    }

    public void mBindService(View view) {
        Intent intent = new Intent(this, ServiceForBind.class);
        bindService(intent, connection, BIND_AUTO_CREATE);
        Log.i(TAG, "mBindService: ");

    }

    public void mUnbindService(View view) {
        Intent intent = new Intent(this, ServiceForBind.class);
        unbindService(connection);
        Log.i(TAG, "mUnbindService: ");
    }

//开启且绑定
    public void mStartandBindService(View view) {
        Intent intent = new Intent(this, ServiceForStartAndBind.class);
        startService(intent);
        bindService(intent, serviceConnection,BIND_AUTO_CREATE);
        Log.i(TAG, "mStartandBindService: ");
    }

    //只关闭
    public void mOnlyStop(View view) {
        Intent intent = new Intent(this, ServiceForStartAndBind.class);
        stopService(intent);
        Log.i(TAG, "mOnlyStop: 只关闭");
    }

    //只解绑
    public void mOnlyUnbind(View view) {
        Intent intent = new Intent(this, ServiceForStartAndBind.class);
        unbindService(serviceConnection);
        Log.i(TAG, "mOnlyUnbind: 只解绑");
    }

    //解绑并关闭
    public void mStopandUnbind(View view) {
        Intent intent = new Intent(this, ServiceForStartAndBind.class);
        stopService(intent);
        unbindService(serviceConnection);
        Log.i(TAG, "mStopandUnbind: 关闭并解绑");
    }

    private class MyServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            //通过返回Ibinder对象作为中介完成对服务里面私有方法的调用
            Log.i(TAG, "onServiceConnected: 绑定服务成功了 ");
            ((ServiceForBind.MyBinder) iBinder).callMethod();

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.i(TAG, "onServiceDisconnected: 解绑服务成功了");
        }
    }
}

ServiceForStart.java代码:

package com.hfut.operationservicelifespace;

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

import java.util.Timer;
import java.util.TimerTask;

public class ServiceForStart extends Service {
    Timer timer;
    private static final String TAG = "ServiceForStart";
    public ServiceForStart() {
    }

    @Override
    public void onCreate() {
        Log.i(TAG, "onCreate: 执行了");
         timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Log.i(TAG, "run: 服务:我还没有被销毁哟");
            }
        },1000,1000);
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand: 执行了");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy: 服务:我gg了");
        timer.cancel();
        super.onDestroy();
    }
}

ServiceForBind.java代码:

package com.hfut.operationservicelifespace;

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

import java.util.Timer;
import java.util.TimerTask;

public class ServiceForBind extends Service {
    private static final String TAG = "ServiceForBind";
    Timer timer;
    public ServiceForBind() {
    }

    //定义一个服务里面的方法
    private void methodInService() {
        Log.i(TAG, "methodInService: 我是服务里面的私有方法,我已经被成功调用了");
    }

    @Override
    public void onCreate() {
        Log.i(TAG, "onCreate: 执行了");
         timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Log.i(TAG, "run: 服务:我还没有被销毁哟");
            }
        },1000,1000);
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand: 执行了");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind: 执行了");
        // TODO: Return the communication channel to the service.
        return new MyBinder();
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy: 服务:我gg了");
        timer.cancel();
        super.onDestroy();
    }

    class MyBinder extends Binder {
        public void callMethod() {
            methodInService();
        }
    }
}

ServiceForStartAndBind.java代码:

package com.hfut.operationservicelifespace;

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

import java.util.Timer;
import java.util.TimerTask;

public class ServiceForStartAndBind extends Service {
    private static final String TAG = "ServiceForStartAndBind";
    Timer timer;
    public ServiceForStartAndBind() {

    }

    @Override
    public void onCreate() {
        timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Log.i(TAG, "run: 服务:我还没有被销毁哟");
            }
        },1000,1000);
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy: 服务:我gg了");
        timer.cancel();
        super.onDestroy();
    }
}

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:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.hfut.operationservicelifespace.MainActivity">

   <Button
       android:layout_marginTop="30dp"
       android:onClick="mStartService"
       android:text="开启服务"
       android:textSize="20dp"
       android:layout_width="match_parent"
       android:layout_height="wrap_content" />
    <Button
        android:layout_marginTop="10dp"
        android:onClick="mStopService"
        android:text="关闭服务"
        android:textSize="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:layout_marginTop="10dp"
        android:onClick="mBindService"
        android:text="绑定服务"
        android:textSize="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:layout_marginTop="10dp"
        android:onClick="mUnbindService"
        android:text="解绑服务"
        android:textSize="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <View
        android:layout_marginTop="20dp"
        android:layout_height="10px" android:background="#ff0000"
        android:layout_width="fill_parent">

    </View>
    <Button
        android:layout_marginTop="10dp"
        android:onClick="mStartandBindService"
        android:text="开启并绑定服务"
        android:textSize="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:layout_marginTop="10dp"
        android:onClick="mOnlyStop"
        android:text="只关闭"
        android:textSize="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:layout_marginTop="10dp"
        android:onClick="mOnlyUnbind"
        android:text="只解绑"
        android:textSize="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:layout_marginTop="10dp"
        android:onClick="mStopandUnbind"
        android:text="解绑并关闭"
        android:textSize="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

主配置文件AndroidManifest.xml代码:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hfut.operationservicelifespace">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".ServiceForStart"
            android:enabled="true"
            android:exported="true" />
        <service
            android:name=".ServiceForBind"
            android:enabled="true"
            android:exported="true" />
        <service
            android:name=".ServiceForStartAndBind"
            android:enabled="true"
            android:exported="true"></service>
    </application>

</manifest>

3,运行结果

第一步:运行程序

第二步:点击“开启服务”,点击“关闭服务”

第三步:点击“绑定服务”,点击“解绑服务”

第四步:点击“开启并绑定服务”,点击“只关闭”,在点击“只解绑”

第五步:点击“开启并绑定服务”,点击“解绑并绑定服务”

由上面可以看出几点:

(1)每次开启服务,都会执行服务的onStartCommand()方法,但是onCreate()只会执行一次

(2)如何开启并绑定了一个服务(主题是活动),那么两者必须同时不满足才能销毁服务

(3)关于服务里面的功能使用,可以尝试用面向接口的方式实现一下(自定义一个接口,在继承Binder的时候同时实现自定义接口,在实现接口方法的时候,把服务的功能放进去;然后就可以通过返回对象转化为自定义接口来面向接口编程了(向上转型))

总结:服务在Android学习中,还是非常重要的概念,基础的东西还是一个仔细研究一下的。本文示例代码链接

注:欢迎扫码关注

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值