Android四大组件之二:Service

1.Android四大组件之一Service

  [1]概念:服务可以长期在后台运行,但是没有用户界面。通常用来控制音乐播放,联网下载等等。


  [2]服务分两种:
               1.非绑定服务
                 startService() --> 启动服务  --> onCreate --> onStartCommand --> running

                 stopService()/stopSelf() --> 销毁服务  --> onDestroy

package com.farsight.unbindservie;

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

public class Android_07_UnbindServiceActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
    }

	@Override
	public void onClick(View v) {
		Intent intent = new Intent();
		intent.setClass(this, MyService.class);
		// TODO Auto-generated method stub
		if(v.getId() == R.id.button1){
			//启动服务
			startService(intent);
		}
		else if(v.getId() == R.id.button2){
			//销毁服务
			stopService(intent);
		}
	}
}
package com.farsight.unbindservie;

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

public class MyService extends Service implements Runnable {

	@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.e("Test", "onCreate");

		// 启动下载线程
		new Thread(this).start();
	}

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

	// 销毁
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.e("Test", "onDestroy");
	}

	int count = 0;

	@Override
	public void run() {
		// TODO Auto-generated method stub

		// 模拟下载
		while (count < 15) {

			count++;

			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		
		// 销毁服务
		this.stopSelf();
<span style="white-space:pre">	</span>}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="启动服务" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="销毁服务" />

</LinearLayout>




               2.绑定服务
                 将服务绑定到Activity组件上。可以实现服务数据向activity传递。
                 Activity销毁,服务也跟着销毁。


                 bindservice() --> 绑定服务 --> onCreate --> onBind --> 返回一个IBinder类型的对象给绑定服务的Activity 
                               --> 系统自动调用onServiceConnected接收IBinder类型的对象 --> 服务running

 ununbindService --> 解除绑定 --> onUnbind--> onDestroy --> 服务销毁

  [3]服务组件运行在主线程中

package com.farsight.bindservice;

import com.farsight.bindservice.MyService.MyBinder;

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.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class Android_08_BindServiceActivity extends Activity implements OnClickListener {
    
	TextView tv;
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
        findViewById(R.id.button3).setOnClickListener(this);
        
        tv = (TextView) findViewById(R.id.textView1);
        
        //输出运行活动组件线程的名字
        Log.e("Test", "thread name = " + Thread.currentThread().getName());
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v.getId() == R.id.button1){
			//绑定服务
			Intent intent = new Intent(this, MyService.class);
			bindService(intent, conn, Context.BIND_AUTO_CREATE);
		}
		else if(v.getId() == R.id.button2){
			//解除绑定
			unbindService(conn);
		}
		else if(v.getId() == R.id.button3){
			//获取下载进度
			Log.e("Test", "count = " + mybinder.getCount());
			
			tv.setText(String.valueOf(mybinder.getCount()));
		}
	}
	
	MyBinder mybinder;
	MyServiceConnection conn = new MyServiceConnection();
	//该类提供了服务向活动传输数据的通道
	class MyServiceConnection implements ServiceConnection
	{

		//当服务成功绑定到活动上时,该方法被调用
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			Log.e("Test", "IBinder = " + service);
			mybinder = (MyBinder)service;
			
		}

		//当服务绑定异常时,该方法被调用
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			
		}
		
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unbindService(conn);
	}
}
package com.farsight.bindservice;

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

public class MyService extends Service implements Runnable {

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

		Log.e("Test", "thread = " + Thread.currentThread().getName());
		
		new Thread(this).start();
	}

	// 绑定服务
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		Log.e("Test", "onBind");
		MyBinder mybinder = new MyBinder();
		Log.e("Test", "mybinder = " + mybinder);
		return mybinder;
	}

	class MyBinder extends Binder {

		public int getCount() {
			return count;
		}

	}

	//解除绑定
	@Override
	public boolean onUnbind(Intent intent) {
		// TODO Auto-generated method stub
		Log.e("Test", "onUnbind");
		return super.onUnbind(intent);
	}

	// 销毁服务
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.e("Test", "onDestroy");
	}

	// 下载进度
	int count;

	@Override
	public void run() {
		// TODO Auto-generated method stub

		while (count < 50) {

			count++;

			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="绑定服务" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="解除绑定" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="获取下载进度" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

你可能感兴趣的:(Android四大组件之二:Service)