通过Binder调用Service内的方法

通过Binder调用Service内的方法

有时候我们会在Android后台服务中执行一些操作,这些操作被封装成方法,因此会有在服务外调用Service内的方法的需求。

Service服务中的代码

package com.songzheng.androidlearning;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.NotificationCompat;
import android.util.Log;

/**
 * Created by make on 2016/11/17.
 */

public class MyService extends Service{

    private static final int NOTIFY_ID = 123;

    private class MyBinder extends Binder implements IService{

        @Override
        public void callShowNotification() {
            showNotification();
        }
    }

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

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void showNotification(){
        NotificationCompat.Builder mBuilder =
                (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.myfirstname)
                        .setContentTitle("2016/11/17")
                        .setContentText("Sunny");

        Intent resultIntent = new Intent(this, MainActivity.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        final Notification notification = mBuilder.build();

        manager.notify(NOTIFY_ID, notification);

        startForeground(NOTIFY_ID, notification);
    }
}

MyService类中定义了一个MyBinder中间人继承自Binder实现了IService接口,在这里MyBinder为private的,其中有个方法可以调用服务内的方法showNotification(),服务被绑定时会回调onBind()方法,因此在这里返回一个MyBinder对象。

IService:

package com.songzheng.androidlearning;

/**
 * Created by make on 2016/11/17.
 */

public interface IService {
    public void callShowNotification();
}

在MainActivity中通过bindService方法指定一个实现了ServiceConnection接口的对象,实现ServiceConnection接口要实现两个方法:onServiceConnected()和onServiceDisconnected()方法,在onServiceConnection()方法中会传递一个IBinder对象,即服务绑定成功是onBind返回的MyBinder对象,强转为IService类型即可调用其中的方法,即实现了调用服务中的方法。

MainActivity:

package com.songzheng.androidlearning;

import android.content.ComponentName;
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;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private MyConn conn;
    private IService myBinder;

    private Button btCall;

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

        Intent intent = new Intent(MainActivity.this, MyService.class);
        conn = new MyConn();
        bindService(intent, conn, BIND_AUTO_CREATE);

        btCall = (Button) findViewById(R.id.bt_call);

        btCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (myBinder != null){
                    myBinder.callShowNotification();
                }
            }
        });
    }

    private class MyConn implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder = (IService) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            myBinder = null;
        }
    }

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

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值