Android四组件之Service&Demo

来源:互联网 发布:java 获取网页源代码 编辑:程序博客网 时间:2024/05/21 03:17

*Service概述*
一、Service(服务)是一个没有用户界面的在后台运行执行耗时操作的应用组件。其他应用组件能够启动Service,并且当用户切换到另外的应用场景,Service将持续在后台运行。另外,一个组件能够绑定到一个service与之交互(IPC机制),例如,一个service可能会处理网络操作,播放音乐,操作文件I/O或者与内容提供者(content provider)交互,所有这些活动都是在后台进行。
Service有两种状态,“启动的”和“绑定”

二、由于手机屏幕的限制,通常情况下在同一时刻仅有一个应用程序处于激活状态,并能够显示在手机屏幕上,因此,应用程序需要一种机制,在没有用户界面的情况下,能够长时间在后台运行,实现应用程序的特定功能,并能够处理事件或更新数据.Android系统提供了(Service)服务组件,它不直接与用户进行交互,却能够长期在后台运行。有很多情况需要使用Service,典型的例子就是:MP3播放器。

三、Service非常适用于无需用户干预,且需要长期运行的后台功能。Service没有用户界面,有利于降低系统资源。而且Service比Activity具有更高的优先级,只有在系统资源极度匮乏的情况下,android系统才可能清理掉一部分service来保证系统的运行,而这种情况却又轻易不会出现。即使Service被系统终止了,在系统资源恢复后Service也将自动恢复运行状态,因此可以认为Service是在系统中永久运行的组件。Service除了实现后台服务功能,还可以用于进程间通信,解决两个不同Activity应用程序进程之间的调用和通信问题。
四、Service的生命周期如下图所示:

这里写图片描述

context.startService() ->onCreate()- >onStartCommand()->Service running–调用context.stopService()->onDestroy()
context.bindService()->onCreate()->onBind()->Service running–调用>onUnbind() -> onDestroy()
从上诉可以知道分别对应本地的,以及远程的,也对应不同的方式启动这个服务。
五、下面我们用简单地例子来讲解一下
如何启动Service(典型的例子就是:MP3播放器。)
界面:
这里写图片描述
xml文件的代码如下:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout    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:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    style="@style/Widget.AppCompat.Button.Borderless"    app:layout_behavior="@string/appbar_scrolling_view_behavior"    tools:context=".MainActivity"    tools:showIn="@layout/activity_main">    <LinearLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:orientation="vertical">        <TextView            android:layout_width="match_parent"            android:layout_height="48dp"            android:layout_gravity="center_horizontal"            android:gravity="center_horizontal|center_vertical"            android:text="@string/hello"            android:textColor="@color/colorYellow"            android:textSize="20dp"            />        <Button            android:id="@+id/start"            android:layout_width="wrap_content"            android:layout_height="48dp"            android:layout_gravity="center_horizontal"            android:layout_marginTop="30dp"            android:background="@drawable/btn_selector"            android:gravity="center_vertical"            android:padding="8dp"            android:text="startService"            android:textColor="@android:color/background_dark"            android:textSize="12dp"/>        <Button            android:id="@+id/stop"            android:layout_width="wrap_content"            android:layout_height="48dp"            android:layout_gravity="center_horizontal"            android:layout_marginTop="20dp"            android:background="@drawable/btn_selector"            android:gravity="center_vertical"            android:padding="8dp"            android:text="stopService"            android:textColor="@android:color/background_dark"            android:textSize="12dp"/>        <Button            android:id="@+id/bind"            android:layout_width="wrap_content"            android:layout_height="48dp"            android:layout_gravity="center_horizontal"            android:layout_marginTop="20dp"            android:background="@drawable/btn_selector"            android:gravity="center_vertical"            android:padding="8dp"            android:text="bindService"            android:textColor="@android:color/background_dark"            android:textSize="12dp"/>        <Button            android:id="@+id/unbind"            android:layout_width="wrap_content"            android:layout_height="48dp"            android:layout_gravity="center_horizontal"            android:layout_marginTop="20dp"            android:background="@drawable/btn_selector"            android:gravity="center_vertical"            android:padding="8dp"            android:text="unBindService"            android:textColor="@android:color/background_dark"            android:textSize="12dp"/>    </LinearLayout></RelativeLayout>

Activity代码如下:
//PS : 哈哈 我加了一个反馈功能,有什么意见可以给我发邮件哈!

package com.one.neo.servicedemo;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.Snackbar;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.view.Menu;import android.view.MenuItem;import android.view.View;/** * @author YuQi on 2015/11/10 16:24 * @function MainActivity */public class MainActivity extends AppCompatActivity implements View.OnClickListener {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);        setSupportActionBar(toolbar);        initView();        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);        fab.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Snackbar.make(view, "Love U !XS", Snackbar.LENGTH_LONG)                        .setAction("Action", null).show();                sendMail();            }        });    }    private void sendMail() {        new Thread(new Runnable() {            @Override            public void run() {                //// TODO: 2015/11/10 硬编码                Intent email = new Intent(Intent.ACTION_SEND);                email.setType("plain/text");                String[] emailReciver = new String[]{"yu163qi@163.com"};                String emailTitle = "关于[ServiceDemo]的反馈";                String emailContent = "欢迎吐槽&拍砖!";                email.putExtra(Intent.EXTRA_EMAIL, emailReciver);                email.putExtra(Intent.EXTRA_SUBJECT, emailTitle);                email.putExtra(Intent.EXTRA_TEXT, emailContent);                startActivity(Intent.createChooser(email, "请选择您的邮件客户端"));            }        }).start();    }    private void initView() {        findViewById(R.id.start).setOnClickListener(this);        findViewById(R.id.stop).setOnClickListener(this);        findViewById(R.id.bind).setOnClickListener(this);        findViewById(R.id.unbind).setOnClickListener(this);    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_main, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }    // new ServiceConnection    final ServiceConnection connection = new ServiceConnection() {        @Override        public void onServiceConnected(ComponentName name, IBinder service) {        }        public void onServiceDisconnected(ComponentName name) {            // TODO Auto-generated method stub        }    };    public void onClick(View v) {        Intent intent = new Intent(MainActivity.this, PlayService.class);        switch (v.getId()) {            // startService()方法开启服务            case R.id.start:                startService(intent);                break;            // stopService()方法停止服务            case R.id.stop:                stopService(intent);                break;            // bindService()方法开启服务            case R.id.bind:                bindService(intent, connection, BIND_AUTO_CREATE);                break;            // unbindService()方法停止服务            case R.id.unbind:                unbindService(connection);                break;            default:                break;        }    }}

Activity的开头部分详细介绍了startService以及bindService用法的区别,这里不再累述。

接下来是Service的代码:

package com.one.neo.servicedemo;import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.os.IBinder;import android.util.Log;/** * @author YuQi on 2015/11/10 16:24 * @function Background PlayService */public class PlayService extends Service {    private MediaPlayer player;    @Override    public void onCreate() {        // TODO Auto-generated method stub        Log.d("music play", "Service onCreat()执行成功");        player = MediaPlayer.create(this, R.raw.test);        // setLooping(boolean);方法,接受的是boolean值        // true 表示循环播放        // false 表示不循环播放        // 默认值为false,即不循环播放        player.setLooping(false);        super.onCreate();    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        // MediaPlayer对象的start()方法        player.start();        Log.d("music play", "Start ");        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        // MediaPlayer对象的stop()方法        player.stop();        Log.v("music play", "Stop");        super.onDestroy();    }    @Override    public boolean onUnbind(Intent intent) {        // MediaPlayer对象的stop()方法        Log.d("music play", "onUnbind");        return super.onUnbind(intent);    }    @Override    public IBinder onBind(Intent intent) {        // MediaPlayer对象的start()方法        player.start();        Log.d("music play", "onBind");        return null;    }}

下面干货来了!就是源码下载,哈哈~

ServiceDemo下载

0 0