创建、配置、启动、停止Service

58 篇文章 1 订阅
45 篇文章 1 订阅

一.创建、配置Service


   开发Service需要两个步骤:

    1.定义一个继承Service的子类。

    2.在AndroidManifest.xml中对Service进行配置。


    Service定义了系列生命周期的方法:

    1.abstract IBinder onBind(Intent intent):该方法必须实现,该方法返回一个IBinder对象,应用程序通过该对象与Service组件通信。

    2.void onCreate():Service第一次被创建时回调该方法。

    3.void onDestroy():Service关闭之前将会回调该方法。

    4.void onStartCommand(Intent intent, int flags, int startId):每次客户端调用startService(intent)方法启动该Service时都会回调该方法。

    5.boolean onUnbind(Intent intent):Service上绑定的所有客户端都断开连接时竟会回调该方法。


二.启动和停止Service

    很简单,使用startService()stopService()方法即可启动和停止Service。


下面给出一个简单的项目实例:


工程结构:





AndroidManifest.xml

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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=".FirstService">
        </service>
    </application>

</manifest>



main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#2b2b2b">

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5pt"
        android:layout_marginRight="5pt"
        android:layout_marginTop="10pt"
        android:text="S T A R T"
        android:textColor="#ffffff"
        android:textSize="8pt"
        android:textStyle="bold"
        android:id="@+id/start"
        android:background="#696969"
        android:layout_gravity="center_horizontal" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5pt"
        android:layout_marginRight="5pt"
        android:layout_marginTop="10pt"
        android:text="S T O P"
        android:textColor="#ffffff"
        android:textSize="8pt"
        android:textStyle="bold"
        android:id="@+id/stop"
        android:background="#696969"
        android:layout_gravity="center_horizontal" />
</LinearLayout>



MainActivity.java

package com.example.leidong.firstservice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
    //按钮声明
    Button start;
    Button stop;

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

        //加载按钮
        start = (Button)findViewById(R.id.start);
        stop = (Button)findViewById(R.id.stop);

        //创建启动Service的Intent
        final Intent intent = new Intent(MainActivity.this, FirstService.class);

        //Start按钮点击监听
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //启动指定的Service
                startService(intent);
            }
        });

        //stop按钮点击监听
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //停止指定的Service
                stopService(intent);
            }
        });

    }
}



FirstService.java

package com.example.leidong.firstservice;

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

/**
 * Created by leidong on 2016/9/3.
 */
public class FirstService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate(){
        super.onCreate();
        System.out.println("Service is created.");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        System.out.println("Service is started.");
        return START_STICKY;
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        System.out.println("Service is destroyed.");
    }
}



AVD运行效果:



点击START按钮后,LogCat中显示



点击STOP按钮后,LogCat显示



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值