package com.example.administrator.test.Fragment.Service; import android.app.IntentService; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.net.Uri; import android.os.IBinder; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Toast; import com.example.administrator.test.R; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.appindexing.Thing; import com.google.android.gms.common.api.GoogleApiClient; public class TestService extends AppCompatActivity { public void bt1_OnClick(View v) { Intent intent = new Intent( this, MyService.class ); intent.putExtra( "test", "发送的数据" ); startService( intent ); Toast.makeText( this, "MyService已启动", Toast.LENGTH_SHORT ).show(); } public void bt2_OnClick(View v) { Intent intent = new Intent( this, MyService.class ); stopService( intent ); Toast.makeText( this, "MyService已停止", Toast.LENGTH_SHORT ).show(); } ServiceConnection sc; MyService.MyBinder myb; //绑定方式 public void bt3_OnClick(View v) { Intent intent = new Intent( this, MyService.class ); if (sc == null) sc = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { //接收代理对象 myb = (MyService.MyBinder) iBinder; Toast.makeText( TestService.this, "绑定启动完成,接收返回的对象,读取到的数据="+myb.getTest(), Toast.LENGTH_SHORT ).show(); } @Override public void onServiceDisconnected(ComponentName componentName) { Toast.makeText( TestService.this, "服务连接断开", Toast.LENGTH_SHORT ).show(); } }; //三个参数:1.意图2.服务连接3.启动方式 bindService( intent, sc, Context.BIND_AUTO_CREATE );//自动创建 } //解除绑定 public void bt4_OnClick(View v) { if (sc!=null) { unbindService( sc ); sc=null; }else { Toast.makeText( this, "清先绑定服务", Toast.LENGTH_SHORT ).show(); } } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="普通方式启动" android:onClick="bt1_OnClick"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="普通方式停止" android:onClick="bt2_OnClick"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="绑定方式启动" android:onClick="bt3_OnClick"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="解绑方式停止" android:onClick="bt4_OnClick"/> </LinearLayout>
时间: 2024-11-11 21:46:20