首页 > 代码库 > 从零开始学android<Service服务.四十三.>

从零开始学android<Service服务.四十三.>

在Android系统开发之中,Services是一个重要的组成部分。如果现在某些程序需要中的部分操作是很消耗时间的,那么可以将这些程序定义在Service之中,这样就可以完成程序的后台运行(也可以在不显示界面的形式下运行),即:Services实际上就相当于是一个没有图形界面的Activity程序,而且当用户要执行某些操作需要进行跨进程访问的时候也可以使用Service来完成。
Service是一个没有UI界面的操作组件,主要的功能是为Activity程序提供一些必要的支持,例如:手机中的Mp3播放软件,当回到桌面上的时候这些组件依然可以运行,实际上这些就属于Service的功能,在开发时用户只需要继承自android.app.Service类就可以完成Service程序的开发,在Service之中也有自己的生命周期方法。

接下来用一个例子来说明下service的生命周期

<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/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="90dp"
        android:text="开启Service" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="100dp"
        android:text="关闭Service" />

</RelativeLayout>

sevice
package com.example.service2;

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

public class MyService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		Log.i("log", "onCreate");
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.i("log", "onDestroy");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		Log.i("log", "onStartCommand");
		return super.onStartCommand(intent, flags, startId);
		
	}

}


主类
package com.example.service2;

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

public class MainActivity extends Activity {
	private Button button1, button2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button1 = (Button) this.findViewById(R.id.button1);
		button2 = (Button) this.findViewById(R.id.button2);
		button1.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			Intent intent=new Intent(MainActivity.this, MyService.class);
			startService(intent);
			}
		});
		button2.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			Intent intent=new Intent(MainActivity.this, MyService.class);
			stopService(intent);
			}
		});
	}

}





将Service与Activity进行绑定操作
<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/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button2"
        android:layout_alignParentTop="true"
        android:layout_marginTop="22dp"
        android:text="开启Service" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/button4"
        android:layout_below="@+id/button4"
        android:layout_marginTop="32dp"
        android:text="关闭Service" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="32dp"
        android:text="绑定Service" />

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="取消绑定" />

</RelativeLayout>
Service
package com.example.service1;

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

public class MyService extends Service {
	private IBinder myBinder = new Binder() {

		@Override
//		service中定义方法
		public String getInterfaceDescriptor() {
			System.out.println("***mybinder");
			return "MyService Class ..";
		}
	};

	@Override
	public IBinder onBind(Intent intent) {
		System.out.println("*** Service onBind()");
		return this.myBinder; // 此处暂时不做任何的处理
	}

	@Override
	public void onRebind(Intent intent) {
		// 重新绑定

		System.out.println("*** Service onRebind()");
		super.onRebind(intent);
	}

	@Override
	public boolean onUnbind(Intent intent) {
		// 解除绑定
		System.out.println("*** Service onUnbind()");
		return super.onUnbind(intent);
	}

	@Override
	public void onCreate() {
		// 创建Service
		super.onCreate();
		System.out.println("*** Service onCreate()");
	}

	@Override
	public void onDestroy() {
		// 销毁service
		super.onDestroy();

		System.out.println("*** Service onDestroy()");

	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId)
	// 执行service
	{
		System.out.println("*** Service onStartCommand");

		return Service.START_CONTINUATION_MASK; // 继续执行
	}

}

MainActivity
package com.example.service1;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
private Button button1,button2,button3,button4;
//将service和ACtivity绑定
private ServiceConnection serviceConnection = new ServiceConnection() {

	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
		try {
			System.out.println("### Service Connect Success . service = "
					+ service.getInterfaceDescriptor());
		} catch (RemoteException e) {
		}
	}

	@Override
	public void onServiceDisconnected(ComponentName name) {
		System.out.println("### Service Connect Failure.");
	}

};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        
        
        button1=(Button)this.findViewById(R.id.button1);
        button2=(Button)this.findViewById(R.id.button2);
        button3=(Button)this.findViewById(R.id.button3);
        button4=(Button)this.findViewById(R.id.button4);
//        开始Service的监听
   button1.setOnClickListener(new View.OnClickListener() {
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
	MainActivity.this.startService(new Intent(MainActivity.this, MyService.class));
	onStart();
	}
});
//   关闭Service的监听
   button2.setOnClickListener(new View.OnClickListener() {
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		MainActivity.this.stopService(new Intent(MainActivity.this, MyService.class));	
		onStop();
	}
});
   
   
   button3.setOnClickListener(new View.OnClickListener() {
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		MainActivity.this.bindService(new Intent(MainActivity.this, MyService.class),  MainActivity.this.serviceConnection,
				Context.BIND_AUTO_CREATE);
	}
});
   button4.setOnClickListener(new View.OnClickListener() {
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
	MainActivity.this.unbindService(serviceConnection);
	}
});
    }
    
}


开启




绑定



解除绑定



销毁service







使用Service获得系统的其他操作

1
public static final String CLIPBOARD_SERVICE
常量
剪贴板服务
2
public static final String WINDOW_SERVICE
常量
窗口服务
3
public static final String ALARM_SERVICE
常量
闹铃服务
4
public static final String AUDIO_SERVICE
常量
音频服务
5
public static final String NOTIFICATION_SERVICE
常量
Notification服务
6
public static final String SEARCH_SERVICE
常量
搜索服务
7
public static final String POWER_SERVICE
常量
电源管理服务
8
public static final String WIFI_SERVICE
常量
WIFI服务
9
public static final String ACTIVITY_SERVICE
常量
运行程序服务

今天,我们就简单用两个例子进行说明

使用Service取得剪贴板服务

<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" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="41dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

</RelativeLayout><strong>
</strong>


package com.example.service3;

import android.os.Bundle;
import android.app.Activity;
import android.content.ClipboardManager;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        获得ClipboardManager对象
 ClipboardManager clipboardManager=(ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
// 设置文字
 clipboardManager.setText("风飞雪未扬");
 
    }
    
}




使用service操作手机Wifi

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<TextView
		android:id="@+id/msg"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content" />
	<Button
		android:id="@+id/open"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:text="打开WIFI" />
	<Button
		android:id="@+id/close"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:text="关闭WIFI" />
	<Button
		android:id="@+id/check"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:text="检查WIFI状态" />
</LinearLayout>

package com.example.service5;
import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
	private Button open = null;				// 按钮组件
	private Button close = null;				// 按钮组件
	private Button check = null;				// 按钮组件
	private TextView msg = null;				// 文本组件
	private WifiManager wifiManager = null;		// wifi管理
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.activity_main);			// 配置布局管理器
		this.open = (Button) super.findViewById(R.id.open);	// 取得组件
		this.close = (Button) super.findViewById(R.id.close);	// 取得组件
		this.check = (Button) super.findViewById(R.id.check);	// 取得组件
		this.msg = (TextView) super.findViewById(R.id.msg);	// 取得组件
		this.wifiManager = (WifiManager) super
				.getSystemService(Context.WIFI_SERVICE);	// 取得Wife服务
		this.open.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				MainActivity.this.wifiManager.setWifiEnabled(true); // 启用Wifi
				MainActivity.this.msg.setText("打开WIFI,状态:"
					+ MainActivity.this.wifiManager.getWifiState());// 设置文字
			}
			});
		this.close.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				MainActivity.this.wifiManager.setWifiEnabled(false); // 关闭WIFI
				MainActivity.this.msg.setText("关闭WIFI,状态:"
					+ MainActivity.this.wifiManager.getWifiState());// 设置文字
			}
		});
		this.check.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				MainActivity.this.msg.setText("检查WIFI,状态:"
					+ MainActivity.this.wifiManager.getWifiState());// 设置文字
			}
		});
	}
}

		





当然,大家在下面可以参照API取得其他服务并进行相应的配置,其他的就不再一一说明。


下节预报:Notification 通知


从零开始学android<Service服务.四十三.>