Bound Service
核心代码:
注册组件(Manifest.xml):
<service android:name="alice.Service2.FirstService"></service>
组件:
public class MyService extends Service{
@Override
public IBinder onBind(Intent arg0) {
IBinder iBinder = new MyBinder();
return iBinder;
}
class MyBinder extends Binder{
public String getName(){
return "zhangsan";
}
}
}
组件调用:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intnet =new Intent();
bindService(intnet, conn, BIND_AUTO_CREATE);
}
ServiceConnection conn=new ServiceConnection() {
public void onServiceConnected(ComponentName arg0, IBinder iBinder) {
MyBinder myBinder=(MyBinder)iBinder;
myBinder.getName();
}
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
}
};
控件图例:
具体应用:
注册组件(Manifest.xml):
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="alice.Service2"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Service2"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--注册service-->
<service android:name="alice.Service2.FirstService"></service>
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>
组件:
package alice.Service2;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class MyService extends Service{
@Override
public IBinder onBind(Intent arg0) {
IBinder iBinder = new MyBinder();
return iBinder;
}
class MyBinder extends Binder{
public String getName(){
return "zhangsan";
}
}
}
组件调用:
package alice.Service2;
import alice.Service2.MyService.MyBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
public class Service2 extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intnet =new Intent();
bindService(intnet, conn, BIND_AUTO_CREATE);
}
ServiceConnection conn=new ServiceConnection() {
public void onServiceConnected(ComponentName arg0, IBinder iBinder) {
MyBinder myBinder=(MyBinder)iBinder;
myBinder.getName();
}
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
}
};
}