【Android】Activity與服務Service綁定

核心代碼

Activity

public class MusicActivity extends Activity implements OnClickListener{
	@Override
	public void onClick(View v) {connection(); }
	private void connection() {
			Intent intent = new Intent("david.bindService");
			bindService(intent, sc, Context.BIND_AUTO_CREATE);
	}
	//在客戶端覆寫onServiceConnected方法,當服務綁定成功會調用此回調函數
	private ServiceConnection sc = new ServiceConnection() {
			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				MyBinder binder = (MyBinder)service; //通過IBinder獲取Service
				musicService = binder.getService();
				if(musicService != null){ musicService.play(); }
			}
		};
	}
}

Service

public class MusicService extends Service {
	//需用內部類繼承Binder,並定義方法獲取Service對象
	private final IBinder binder = new MyBinder();
	public class MyBinder extends Binder {
		BindMusicService getService() {
			return BindMusicService.this;
		}
	}
	@Override
	public IBinder onBind(Intent intent) {//當客戶端調用bindService()方法時調用此函數
		return binder;
	}
	@Override
	public void onCreate() { }
	@Override
	public void onDestroy() { }
}


應用範例

Activity文件

package com.app.myservice;

import com.app.myservice.service.MyService;
import com.app.myservice.service.MyService.MyBind;

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

public class ServiceDemo03_Bind extends Activity implements OnClickListener{
	private Button startservice,stopservice,binderservice,unbinderservice,getService;
	private boolean mIsBound;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_first);
		
		startservice = (Button) findViewById(R.id.button1);
		stopservice = (Button) findViewById(R.id.button2);
		binderservice = (Button) findViewById(R.id.button3);
		unbinderservice = (Button) findViewById(R.id.button4);
		getService = (Button) findViewById(R.id.button5);
		
		startservice.setOnClickListener(this);
		stopservice.setOnClickListener(this);
		binderservice.setOnClickListener(this);
		unbinderservice.setOnClickListener(this);
		getService.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(ServiceDemo03_Bind.this,MyService.class);
		switch (v.getId()) {
		case R.id.button1:
			startService(intent);
			break;
		case R.id.button2:
			stopService(intent);
			break;
		case R.id.button3:
			//綁定Service
			//BIND_AUTO_CREATE表示自動創建
			bindService(intent, connection, BIND_AUTO_CREATE);
			mIsBound = true;
			break;
		case R.id.button4:
			//解除綁定Service
			if (mIsBound == true) {
				unbindService(connection);
			}
			mIsBound = false;
			break;
		case R.id.button5:
			//提示框
			Toast.makeText(ServiceDemo03_Bind.this, "當前Service的值爲"+mService.getIndex(), 1000).show();
			break;
		default:
			break;
		}
	}
 
	private MyService mService = new MyService();
	ServiceConnection connection = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			Toast.makeText(ServiceDemo03_Bind.this, "這裏是:onServiceDisconnected", 1000).show();
		}
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			Toast.makeText(ServiceDemo03_Bind.this, "這裏是:onServiceConnected", 1000).show();
			System.out.println("onServiceConnected");
			MyService.MyBind myBind = (MyBind) service;
			mService = myBind.getMyService();
		}
	};
}

Service文件

package com.app.myservice.service;

import java.util.Timer;
import java.util.TimerTask;

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

public class MyService extends Service{
	private Timer timer;
	private TimerTask task;
	private int index=0;
	Context context;
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return mBind;
	}
	private MyBind mBind = new MyBind();
	public class MyBind extends Binder {
		public MyService getMyService() {
			return MyService.this;
		}
	}                                                
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		context = getApplicationContext();
		Toast.makeText(context, "這裏是:onCreate", 1000).show();
		System.out.println("onCreate");
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		System.out.println("onStartCommand");
		Toast.makeText(context, "這裏是:onStartCommand", 1000).show();
		startTimer();
		return super.onStartCommand(intent, flags, startId);
	}
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		System.out.println("onDestroy");
		Toast.makeText(context, "這裏是:onDestroy", 1000).show();
		super.onDestroy();
		stopTimer();
	}
	
	public void startTimer() {
		timer = new Timer();
		task = new TimerTask() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				index++;
				System.out.println(index);
			}
		};
		// 安排指定的任務從指定的延遲後開始進行重複的固定延遲執行
		timer.schedule(task, 1000, 1000);
	}
	public void stopTimer() {
		timer.cancel();//取消此計時器任務
	}
	public int getIndex() {
		return index;
	}
}

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=".FirstActivity"
    android:background="#fff" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="38dp"
        android:layout_marginTop="14dp"
        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:text="停止cervice" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button2"
        android:layout_below="@+id/button2"
        android:text="綁定service" />

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button3"
        android:layout_below="@+id/button3"
        android:text="解除綁定service" />

    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button4"
        android:layout_below="@+id/button4"
        android:text="獲取service" />

</RelativeLayout>


發佈了128 篇原創文章 · 獲贊 36 · 訪問量 85萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章