Android Api Demos登顶之路(五十四)Service LocalService Binding

这个demo演示了如何如何利用bindService的方式启动一个本地服务,并实现与服务之间的通讯。
* 本例中所指的本地服务就是启动服务的组件与服务处于同一个应用进程当中。
* 其实在上个例子中我们已经实现了这个demo这里再和大家一起简单回顾一下这个流程:
* 1.创建一个继承Service的服务类
* 2.实现onBind方法,并返回一个代理,这里返回服务本身的实例
* 3.实现服务的功能
* 4.在客户端(activity)定义服务类的实例
* 5.建立与服务的连接,并实现两个方法
* 6.使用bindService启动服务
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"
    android:padding="5dp" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/hello_world" />
    <Button 
        android:layout_marginTop="10dp"
        android:id="@+id/binding"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Binding Service"
        android:layout_gravity="center_horizontal"/>
    <Button 
        android:id="@+id/unbinding"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Unbinding Service"
        android:layout_gravity="center_horizontal"/>

</LinearLayout>

LocalService

public class LocalService extends Service {
    private NotificationManager mNM;
    private static final int NOTIFICATION_ID = R.string.hello_world;

    @Override
    public void onCreate() {
        super.onCreate();
        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        showNotification();
    }

    private void showNotification() {
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
        Notification.Builder builder=new Builder(this);
        builder.setSmallIcon(R.drawable.ic_launcher)
               .setTicker("服务已经启动!")
               .setContentTitle("Local Service")
               .setContentText("This is the notification of a service")
               .setContentIntent(contentIntent)
               .setWhen(System.currentTimeMillis())
               .setDefaults(Notification.DEFAULT_ALL);
        Notification noti=builder.build();
        mNM.notify(NOTIFICATION_ID, noti);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 我们希望服务一直运行,当服务被意外杀死时仍然能够重新启动,所以设置返回值为:START_STICKY
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mNM.cancel(NOTIFICATION_ID);
        Toast.makeText(this, "服务已经停止!", 0).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    class MyBinder extends Binder {
        public LocalService getService() {
            return LocalService.this;
        }
    }

}

MainActivity

public class MainActivity extends Activity implements OnClickListener {
    private LocalService mService;
    private boolean isBound;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button bt_binding = (Button) findViewById(R.id.binding);
        Button bt_unbinding = (Button) findViewById(R.id.unbinding);
        bt_binding.setOnClickListener(this);
        bt_unbinding.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.binding:
            doBind();
            break;
        case R.id.unbinding:
            doUnBind();
            break;
        }
    }

    private ServiceConnection conn=new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService=null;
            Toast.makeText(MainActivity.this, "与服务断开连接!", 0).show();
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService=((LocalService.MyBinder)service).getService();
            Toast.makeText(MainActivity.this, "与服务建立连接!", 0).show();
        }
    };

    private void doUnBind() {
        if(isBound){
            unbindService(conn);
            isBound=false;
        }
    }

    private void doBind() {
        Intent intent=new Intent(this, LocalService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
        isBound=true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        doUnBind();
    }
}

配置文件

<service android:name="com.fishtosky.localservice.LocalService"></service>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值