Android四大组件之服务(一)-----服务基础功能简述

服务(Service)是android的四大组件之一,在Android项目中担任着后台运行的大任,主要去完成那些不需要和用户交互而且还要求长时间运行在后台的工作。服务的运行不会对用户使用app造成任何影响,这个组件属于很常用的组件,几乎每一款app产品都会用到,比如后台更新天气,这个动作是在我们毫无察觉的情况下替我们完成的。今天就学习一下,服务的基本用户。


效果图:


代码:

layout文件夹下activity_main.xml代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/stop_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/start_service"
        android:layout_alignBottom="@+id/start_service"
        android:layout_toRightOf="@+id/start_service"
        android:text="关闭服务" />

    <Button
        android:id="@+id/start_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="42dp"
        android:layout_marginTop="24dp"
        android:text="启动服务" />

    <Button
        android:id="@+id/bind_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/start_service"
        android:layout_below="@+id/start_service"
        android:layout_marginTop="24dp"
        android:text="绑定服务" />

    <Button
        android:id="@+id/unbind_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/bind_service"
        android:layout_alignLeft="@+id/stop_service"
        android:text="解绑服务" />

</RelativeLayout>

MainActivity.java中的代码:

package com.demo.myservicedemo;

import com.demo.myservicedemo.MyService.DownloaderBinder;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
	
	private static final String TAG = "MyService" ;
	
	private Button startService;
	private Button stopService;
	private Button bindService;
	private Button unbindService;
	/**
	 * 创建MyService中DownloaderBinder类的对象
	 */
	private MyService.DownloaderBinder downloadBinder;
	/**
	 * 是否绑定服务 true:绑定;false未绑定
	 */
	private boolean is_bindService = false ;
	/**
	 * 实例化MyServiceConnection类
	 */
	private MyServiceConnection connection = new MyServiceConnection();

	/**
	 * 新建一个MyServiceConnection类,实现ServiceConnection接口
	 * 
	 * @author honey
	 */
	class MyServiceConnection implements ServiceConnection {

		/**
		 * 活动与服务成功绑定时调用
		 */
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			/**
			 * 获得MyService中onBind方法返回的实例对象dbinBinder, 获得dbinBinder对象后,
			 * 就可以在activity中操作Myservice中内部类DownloaderBinder中的方法了
			 */
			Log.d(TAG, "MainActivity中onServiceConnected()方法") ;
			Toast.makeText(MainActivity.this, "服务绑定成功,Activity开始与服务通信", 0).show() ;
			is_bindService = true ;//绑定服务的标志
			/**
			 * 向下转型,实例化MyService中DownloaderBinder类的实例
			 */
			downloadBinder = (DownloaderBinder) service;
			downloadBinder.startDownload();
			downloadBinder.getProgress();
		}

		/**
		 * 1、service的连接意外丢失时调用该方法,比如当service崩溃了或被强杀了.
		 * 2、客户端解除绑定(即调用unbindService()这个方法)时,只会调用服务中的onDestroy()方法,不会调用onServiceDisconnected()方法.
		 */
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			Log.d(TAG, "MainActivity中onServiceDisconnected()方法") ;
		}

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		startService = (Button) findViewById(R.id.start_service);
		stopService = (Button) findViewById(R.id.stop_service);
		startService.setOnClickListener(this);
		stopService.setOnClickListener(this);
		bindService = (Button) findViewById(R.id.bind_service);
		unbindService = (Button) findViewById(R.id.unbind_service);
		bindService.setOnClickListener(this);
		unbindService.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.start_service:
			/**
			 * 调用startService()方法,相应的服务就会启动,并回调onStartCommond()方法,
			 * 如果这个服务之前没有创建过,那么onCreate()方法会先于onStartCommond()执行,
			 * 如果这个服务之前创建过,则不再执行onCreate()方法。
			 * 注:因为每个服务只存在一个实例,所以,不管我们调用多少次startService()方法,
			 * 只要调用一次stopService()或stopSelf()方法,服务就会停止
			 */
			Intent startIntent = new Intent(this, MyService.class);
			startService(startIntent); // 启动服务
			Toast.makeText(this, "服务启动", 0).show() ;
			break;
		case R.id.stop_service:
			/**
			 * 调用stopService()方法,会进入Service类的onDestroy()方法中,停止服务
			 */
			Intent stopIntent = new Intent(this, MyService.class);
			stopService(stopIntent); // 停止服务
			Toast.makeText(this, "服务停止", 0).show() ;
			break;
		case R.id.bind_service:// 绑定服务
			/**
			 * 通过bindSerbice()方法将MainActivity和MyService进行绑定,获取一个服务的持久连接,会回调服务中的onBind()方法。
			 * 如果服务还未创建,则会先调用onCreate()方法,然后通过onBind()方法获得IBinder对象,这样就可以操作服务了
			 *  BIND_AUTO_CREATE表示在活动和服务进行绑定后自动 创建服务。
			 *  自动创建服务-->MyService类中的onCreate()方法得到执行,onStartCommand()方法不会执行
			 */
			Intent bindIntent = new Intent(this, MyService.class);
			bindService(bindIntent, connection, BIND_AUTO_CREATE);
			Toast.makeText(this, "绑定服务", 0).show() ;
			break;
		case R.id.unbind_service:// 解除绑定
			/**
			 * unbindService()方法,回调服务中的onDestroy()方法
			 */
			if(is_bindService) {
				unbindService(connection);
				is_bindService = false ;//没有绑定的服务了
				Toast.makeText(this, "解除绑定", 0).show() ;
			}else {
				Toast.makeText(getApplicationContext(), "还没有绑定的服务", 0).show() ;
			}
			break;
		default:
			break;
		}
	}

}

MyService.java中的代码:

package com.demo.myservicedemo;

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

public class MyService extends Service {

	private static final String TAG = "MyService";

	/**
	 * 创建DownloaderBinder实例
	 */
	private DownloaderBinder dbinBinder = new DownloaderBinder();

	/**
	 * 新建DownloaderBinder类,继承自Binder,在该类中提供两个方法:开始下载和查看下载进度
	 * @author honey
	 */
	class DownloaderBinder extends Binder {

		/**
		 * 自定义开始下载的方法
		 */
		public void startDownload() {
			Log.d(TAG, "startDownload");
		}

		/**
		 * 自定义获得下载进度的方法
		 */
		public int getProgress() {
			Log.d(TAG, "getProgress");
			return 0;
		}
	}

	/**
	 * 返回DownloaderBinder类的实例,Activity可以使用这个实例与服务Service进行交互
	 */
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return dbinBinder;
	}

	/**
	 * 在服务第一次创建的时候调用,只调用一次,服务只要启动了,以后再次进入服务就不在进入该方法
	 */
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		Log.d(TAG, "onCreate");
	}

	/**
	 * 每次服务启动的时候调用,不管服务是否启动,每次进入服务都会执行该方法
	 */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		Log.d(TAG, "onStartCommand");
		return super.onStartCommand(intent, flags, startId);
	}

	/**
	 * 服务销毁的时候 调用
	 * 1、如果只调用的startService()启动方法,那么调用stopService()方法即可停止服务;
	 * 2、如果只调用了bindService()方法绑定服务,那么回调unbindService()方法即可解除与服务的绑定;
	 * 3、如果同时调用了startService()方法启动服务,bindService()方法绑定服务,
	 * 那么要同时调用stopService()方法和unbindService()方法,onDestroy()方法才能执行,
	 * 没有先后顺序,而且,只有在第二个方法被调用后,才会进入到onDestroy()方法中
	 */
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.d(TAG, "onDestroy");
	}

}

AndroidManifest.xml中代码:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.demo.myservicedemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.demo.myservicedemo.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <service android:name="com.demo.myservicedemo.MyService" >
        </service>
    </application>

</manifest>


下载demo:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值