标签:
绑定service需要在上一讲中,新创建一个AIDL。
// AppServiceRemoteBinder.aidl package com.example.yabushan.aidsservice; // Declare any non-default types here with import statements interface AppServiceRemoteBinder { /** * Demonstrates some basic types that you can use as parameters * and return values in AIDL. */ void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString); }
在服务类中的onBind方法返回这个新创建的AIDL(可能需要rubuild project)
package com.example.yabushan.aidsservice; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException; public class AppService extends Service { public AppService() { } @Override public IBinder onBind(Intent intent) { return new AppServiceRemoteBinder.Stub(){ @Override public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException { } }; } @Override public void onCreate() { super.onCreate(); System.out.println("service on start"); } @Override public void onDestroy() { super.onDestroy(); System.out.println("service deastroy"); } }
package com.example.yabushan.anotherapp; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity implements View.OnClickListener, ServiceConnection { private Intent serviceIntent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); serviceIntent=new Intent(); serviceIntent.setComponent(new ComponentName("com.example.yabushan.aidsservice","com.example.yabushan.aidsservice.AppService")); findViewById(R.id.startService).setOnClickListener(this); findViewById(R.id.stopService).setOnClickListener(this); findViewById(R.id.BindService).setOnClickListener(this); findViewById(R.id.unBindService).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.startService: startService(serviceIntent); break; case R.id.stopService: stopService(serviceIntent); break; case R.id.BindService: bindService(serviceIntent,this, Context.BIND_AUTO_CREATE); break; case R.id.unBindService: unbindService(this); break; } } @Override public void onServiceConnected(ComponentName name, IBinder service) { System.out.println("bind service"); System.out.println(service); } @Override public void onServiceDisconnected(ComponentName name) { } }
标签:
原文地址:http://www.cnblogs.com/yabushan/p/4990139.html