android ---Service解析

一:Service的概述

   Service是Android四大组件中与Activity最相似的组件。都代表执行的程序,Service与Activity的区别在于:

   Service一直在后台运行,它没有用户界面,所以绝不会到前台来。一旦Service被启动起来之后,它就与Activity一样。完全具有自己的生命周期。

   关于程序中Activity和service的选择标准:

   如果某个程序组件需要在运行时向用户呈现某种界面,或者该程序需要与用户交互,就需要使用Activity,否则就应该考虑使用Service了。

   如:下载东西,播放音乐。可以一边下载,一边播放,一边玩其他的事情。但是Activity是无法做到的。只要Activity被关闭或者最小化了,程序就停止了。


二:特点

1.没有UI

2.进行耗时较长或者与用户没有交互的一些功能

3.Service具有较高的优先级,比stop的Activity优先级要高,最高的优先级是前台Activity

4.具有较长的生命周期

 

三:Service的使用

1)创建:

 创建类继承Service,实现OnBind()方法。

  Service与Activity都是从Context派生出来的。

  因此可以使用Context中的方法,如getResouces()等方法。

2)配置:

 在配置文件中配置<service/>标签

 设置android:name属性,也可以配置<intent-filter>元素

 

 

 

3)启动:

Service启动依赖于其他组件,可以使用Activity或者Receiver等作为调用者,调用者可以使用以下两种形式启动Service

(1)startService

  startService启动Service涉及生命周期方法:

    onCreate()--onStartCommand()/onStart()--onDestory()

 a)onCreate()创建Service实例时的回调函数,启动的Service实例如果不存在会触发一次之后不会触发.

 b)onStartCommand()  启动Service时的回调函数每次启动都会触发,可以通过参数startId获取其启动次数,第二个参数flags表示启动服务的方式: 

 c)onStart():启动Service时,已经被淘汰了。

 d)onDestory(): 销毁 Service 实例



代码示例:

MainActivity.java

package com.example.servicetest;

import com.example.servicetest.FirstService.MyBinder;

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.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	private MyBinder myBinder;
	private ServiceConnection conn = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			System.out.println("连接失败");
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			System.out.println("连接成功");
			myBinder = (MyBinder)service;
		}
	};
	public void btn(View view){
		Intent intent = new Intent(this,FirstService.class);
		startService(intent);
	
	}
	public void btn4(View view){
		Intent intent = new Intent(this,FirstService.class);
		stopService(intent);
	
	}
	
	public void btn1(View view){
		Intent intent = new Intent(this,FirstService.class);
		bindService(intent, conn, BIND_AUTO_CREATE);
		
	}
	
	public void btn2(View view){
		unbindService(conn);
	}
	
	public void btn3(View view){
		Toast.makeText(this, myBinder.getCount()+"", Toast.LENGTH_SHORT).show();
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
	
}

FirstService.java

package com.example.servicetest;

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

public class FirstService extends Service{
	
	private boolean flag = true;
	private int count = 1;
	
	class MyBinder extends Binder{
		public int getCount(){
			return count;
		}
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		new Thread(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(flag){
					try {
						sleep(1000);
						System.out.println(count++);
						if(count == 100) flag = false;
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}.start();
		return new MyBinder();
	}
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		Toast.makeText(this, "服务开启", Toast.LENGTH_SHORT).show();
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		System.out.println("destroy");
		Toast.makeText(this, "服务关闭", Toast.LENGTH_SHORT).show();
		flag = false;
		super.onDestroy();
	}
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    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="com.example.servicetest.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
	<Button 
	    android:text="开启服务"
	    android:onClick="btn"
	    android:layout_width="match_parent"
	    android:layout_height="50dp"/>
	<Button 
	    android:text="停止服务"
	    android:onClick="btn4"
	    android:layout_width="match_parent"
	    android:layout_height="50dp"/>
	<Button 
	    android:text="绑定"
	    android:onClick="btn1"
	    android:layout_width="match_parent"
	    android:layout_height="50dp"/>
	<Button 
	    android:text="解除绑定"
	    android:onClick="btn2"
	    android:layout_width="match_parent"
	    android:layout_height="50dp"/>
	<Button 
	    android:text="获取service数据"
	    android:onClick="btn3"
	    android:layout_width="match_parent"
	    android:layout_height="50dp"/>
</LinearLayout>



结果图: 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值