/***
*
* 1.用Intent在Service和Activity之間傳遞數據:從activity傳到Service
* 2.用Binder在Service和Activity之間傳遞數據:MainActivity拿到返回的Binder後,可以調用裏面的方法,進行業務需求,如改變 Service裏面變量的值
* 3.自定義一個接口,監聽Service的數據變化,要使用Handler來傳遞數據,可以改變activity裏面的東西
*
*/
跑起來的時候:
工程概況:
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:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView android:text="@string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tvCjc"/>
<TextView android:text="@string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tvOut"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edtData"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnStartService"
android:text="啓動服務"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnStopService"
android:text="停止服務"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnBindService"
android:text="綁定服務"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnUbBindService"
android:text="解綁服務"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnSynService"
android:text="同步數據"/>
</LinearLayout>
MainActivity:
package ivo_chuanzhi.connect_service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
/***
*
* 1.用Intent在Service和Activity之間傳遞數據:從activity傳到Service
* 2.用Binder在Service和Activity之間傳遞數據:MainActivity拿到返回的Binder後,可以調用裏面的方法,進行業務需求,如改變Service裏面的值
* 3.自定義一個接口,監聽Service的數據變化,要使用Handler來傳遞數據,可以改變activity裏面的東西
*
*/
public class MainActivity extends ActionBarActivity implements View.OnClickListener{
private Intent intent;
private String data = "傳遞給Service的數據";
EditText edtData;
TextView tvOut,tvCjc;
Button btnStart,btnStop,btnBind,btnUnBind,btnSyn;
private MyService.MyBinder binder = null;
private String Cjc = null;
/****************************onCreate************************/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//操作的是同一個Service,不管是一個Intent實例啓動還是兩個Intent實例
intent = new Intent(MainActivity.this, MyService.class);
tvCjc = (TextView) findViewById(R.id.tvCjc);
tvOut = (TextView) findViewById(R.id.tvOut);
btnStart = (Button) findViewById(R.id.btnStartService);
btnStop = (Button) findViewById(R.id.btnStopService);
btnBind = (Button) findViewById(R.id.btnBindService);
btnUnBind = (Button) findViewById(R.id.btnUbBindService);
btnSyn = (Button) findViewById(R.id.btnSynService);
edtData = (EditText) findViewById(R.id.edtData);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
btnBind.setOnClickListener(this);
btnUnBind.setOnClickListener(this);
btnSyn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnStartService:
//啓動服務:1、startServicer 2、綁定服務
data = edtData.getText().toString();
intent.putExtra("data",data);
startService(intent);
break;
case R.id.btnStopService:
//停止服務
stopService(intent);
break;
case R.id.btnBindService:
//綁定服務
bindService(intent, conn, Context.BIND_AUTO_CREATE);
break;
case R.id.btnUbBindService:
//解除綁定
unbindService(conn);
break;
case R.id.btnSynService:
//同步數據
if(binder != null){
//通訊,改變MyService的data值
binder.setData(edtData.getText().toString());
}
break;
}
}
ServiceConnection conn = new ServiceConnection() {
//服務被綁定成功的時候回調
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
System.out.println("綁定成功");
//連接後會返回MyBinder,連接Service通訊
binder = (MyService.MyBinder) service;
Cjc = binder.getCjc();
tvCjc.setText(Cjc);
//通過binder,get到MyService,然後調用srtCallback方法,實現Callback接口,然後就可以實現監聽監聽Service的數據變化
binder.getMyService().setCallback(new MyService.Callback() {
@Override
public void onDataChange(String data) {
//用Handler來傳遞,不能直接傳遞
Message msg = new Message();
Bundle b = new Bundle();
b.putString("data", data);
msg.setData(b);
handler.sendMessage(msg);
}
});
}
//被綁定的服務斷線時候會回調
@Override
public void onServiceDisconnected(ComponentName name) {
System.out.println("綁定失敗");
}
};
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
tvOut.setText(msg.getData().getString("data"));
}
};
}
MyService:
package ivo_chuanzhi.connect_service;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class MyService extends Service {
private boolean ServicerRunning = false;
private String data = "這是默認信息";
public MyService() {
}
//Service都必須實現的方法
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
//沒綁定的話
//throw new UnsupportedOperationException("Not yet implemented");
//如果實現了綁定了,需要實現onBind接口,返回一個Binder對象,通過Binder可以實現與綁定的activity通訊
// return new MyBinder();//可以重寫Binder,方便業務與activity通訊,向activity傳各種業務數據,重寫或自己寫各種方法,滿足業務的需要
MyBinder binder = new MyBinder();
return binder;
}
public class MyBinder extends Binder{
private String cjc = "努力提高自己的技術";
public String getCjc(){
return cjc;
}
public void setData(String data){
MyService.this.data = data;
}
public MyService getMyService(){
return MyService.this;
}
}
//在activity裏面啓動了startService(new Intent(MainActivity.this, MyService.class));
//的方法都會回調這個函數,可重複執行
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("===onStartCommand===");
data = intent.getStringExtra("data");
return super.onStartCommand(intent, flags, startId);
}
//創建服務後第一個回調該函數,只執行一次
@Override
public void onCreate() {
super.onCreate();
System.out.println("我的服務被創建了");
ServicerRunning = true;
new Thread() {
@Override
public void run() {
super.run();
int i = 0;
while (ServicerRunning) {
i++;
String str = i + ":" + data;
System.out.println(str);
if(callback != null){
callback.onDataChange(str);//在循環中不停的被調用,MainActivity那邊會不停地回調
}
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
//stopService被執行後會回調
@Override
public void onDestroy() {
//stopService和UnBind都會關掉服務
System.out.println("我的服務被關掉了");
ServicerRunning = false;
}
//通知外界的接口
public static interface Callback{
//爲實現的方法
void onDataChange(String data);
}
private Callback callback = null;
public void setCallback(Callback callback){
this.callback = callback;
}
public Callback getCallback(){
return callback;
}
}