activity 与 service 之间的通信

activity和service通信:通过binder

举个我实际项目中的例子:在service中下载更新应用

首先是下载更新apk的service:

public class UpdateVersionService extends Service {

    private final String tag = "young";
    private Context context = this;
    private BaseApplication application;
    private DownloadBinder binder;
    private String apkUrl;// apk下载地址
    private String saveFileName;// 下载安装包路径
    private Thread downLoadThread;// 下载apk线程
    private int progress;// 进度条
    private final int NOTIFY_ID = 0;
    private NotificationManager notificationManager;
    private Notification notification;// 消息通知
    private Builder builder = null;
    private boolean canceled;
    private boolean serviceIsDestory = false;
    private int lastRate = 0;

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    //  Log.v(tag, "success---");下载完成并安装
                    application.setDownload(false);
                    notificationManager.cancel(NOTIFY_ID);
                    installApk();
                    break;
                case 1:
                    int rate = msg.arg1;
                    //   Log.v(tag, "rate---");刷新进度
                    application.setDownload(true);
                    if (rate < 100) {
                        RemoteViews remoteView = notification.contentView;
                        remoteView.setTextViewText(R.id.tv_progress, rate + "%");
                        remoteView.setProgressBar(R.id.progressbar, 100, rate,
                                false);
                    } else {
                        //    Log.v(tag, "下载完成");
                        notification.flags = Notification.FLAG_AUTO_CANCEL;
                        Intent intent = new Intent(context, MainActivity.class);
                        PendingIntent contentIntent = PendingIntent.getActivity(
                                context, 0, intent,
                                PendingIntent.FLAG_UPDATE_CURRENT);
                        builder.setContentTitle(getResources().getString(
                                R.string.download_finish_title));
                        builder.setContentText(getResources().getString(
                                R.string.download_finish_text));
                        notification.contentIntent = contentIntent;
                        serviceIsDestory = true;
                        stopSelf();
                    }
                    notificationManager.notify(NOTIFY_ID, notification);
                    break;
                case 2:
                    // Log.v(tag, "cancel---");取消下载
                    application.setDownload(false);
                    notificationManager.cancel(NOTIFY_ID);
                    break;
                case 3:
                    // Log.v(tag, "error---");出现异常
                    application.setDownload(true);
                    notificationManager.cancel(NOTIFY_ID);
                    Toast.makeText(context,
                            getResources().getString(R.string.download_alter),
                            Toast.LENGTH_SHORT).show();
                    stopSelf();
                    break;
            }

        };
    };

    /**
     * 安装APK
     */
    private void installApk() {
        File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            ToastUtil.toasts(context,
                    getResources().getString(R.string.download_alter));
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.parse("file://" + apkfile.toString()),
                "application/vnd.android.package-archive");
        startActivity(intent);
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        //  Log.v(tag, "onCreate");
        application = (BaseApplication) getApplication();
        this.binder = new DownloadBinder();
        notificationManager = (NotificationManager) this
                .getSystemService(android.content.Context.NOTIFICATION_SERVICE);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        //  Log.v(tag, "onStartCommand");
        apkUrl = intent.getStringExtra("apkUrl");
        if (!StringUtil.isEmpty(apkUrl)) {
            saveFileName =  FileUtils.getAppPath(context, apkUrl).getPath();
        }
        return super.onStartCommand(intent, flags, startId);

    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        //Log.v(tag, "onDestroy");
        application.setDownload(false);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // Log.v(tag, "onBind");
        return binder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        //  Log.v(tag, "onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        //  Log.v(tag, "onRebind");
        super.onRebind(intent);
    }

    /**
     * 下载binder
     *
     * @author Administrator
     *
     */
    public class DownloadBinder extends Binder {

        public void start() {
            if (downLoadThread == null || !downLoadThread.isAlive()) {
                setNotification();
                canceled = false;
                startDownloadApk();
            }
        }

        public void cancel() {
            canceled = true;
        }

        public int getProgress() {
            return progress;
        }

        public boolean getCanceled() {
            return canceled;
        }

        public boolean isDestoryService() {
            return serviceIsDestory;
        }

        public void cancleNotification() {
            handler.sendEmptyMessage(2);
        }
    }

    /**
     * 下载apk
     */
    private void startDownloadApk() {
        downLoadThread = new Thread(downApkRunnable);
        downLoadThread.start();
    }

    private Runnable downApkRunnable = new Runnable() {

        @Override
        public void run() {
            try {
                URL url = new URL(apkUrl);
               // Log.v(tag, "apkUrl---" + apkUrl);
                HttpURLConnection connection = (HttpURLConnection) url
                        .openConnection();
                connection.connect();
                int length = connection.getContentLength();
                InputStream inputStream = connection.getInputStream();
                String apkUrls = saveFileName;
               // Log.v(tag, "apkUrls---" + apkUrls);
                File apkFile = new File(apkUrls);
                if(apkFile.exists()){
                    Log.v(tag, "true---" + apkFile.getAbsolutePath());
                }
                FileOutputStream outputStream = new FileOutputStream(apkFile);
                int count = 0;
                byte[] buffer = new byte[1024];
                do {
                    int readNum = inputStream.read(buffer);
                    count += readNum;
                    progress = (int) (((float) count / length) * 100);
                    Message msg = new Message();
                    msg.what = 1;
                    msg.arg1 = progress;
                    if (progress > lastRate + 1) {
                        handler.sendMessage(msg);
                        lastRate = progress;
                    }
                    if (readNum <= 0) {
                        handler.sendEmptyMessage(0);
                        canceled = true;
                        break;
                    }
                    outputStream.write(buffer, 0, readNum);
                } while (!canceled);
                if (outputStream != null) {
                    outputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                Log.d("young","Exception...."+ e.toString())  ;
                handler.sendEmptyMessage(3);
            }

        }
    };

    /**
     * 设置下载通知栏
     */
    private void setNotification() {
        // String tickerText = getResources().getString(R.string.download_start);
        String tickerText = "开始下载";
        long when = System.currentTimeMillis();
        builder = new Builder(this);
        builder.setSmallIcon(R.drawable.ic_launcher);
        builder.setWhen(when);
        builder.setTicker(tickerText);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            notification = builder.build();
        }
        notification.flags = Notification.FLAG_ONGOING_EVENT;
        RemoteViews contentView = new RemoteViews(getPackageName(),
                R.layout.download_notification_layout);
        contentView.setTextViewText(R.id.tv_name,
                getResources().getString(R.string.download_title));
        notification.contentView = contentView;
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        notification.contentIntent = contentIntent;
        notificationManager.notify(NOTIFY_ID, notification);
    }

}

调用如上service:

声明binder对象:

private UpdateVersionService.DownloadBinder binder;

通过intent绑定service:

 Intent intent =new Intent(mContext, UpdateVersionService.class);
            intent.putExtra("apkUrl",apk_url);
            mContext.startService(intent);
            mContext.bindService(intent,conn, Context.BIND_AUTO_CREATE);
ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            binder = (UpdateVersionService.DownloadBinder) service;
            // 开始下载
            binder.start();
        }
    };

如上在onserviceConnected中调用binder.start(),也就是调用DownloadBinder的start()方法;

start方法里面调用startDownloadApk()开启下载应用的线程,在线程里面通过hander控制Notifition上面进度显示,下载完成调用安装apk程式。

注意在mainfest文件中注册service:

<service android:name="com.chexiu.service.UpdateVersionService" >
        </service>

service与activity通信:通过广播

时间: 2024-12-20 12:26:59

activity 与 service 之间的通信的相关文章

使用Messenger进行Activity与Service之间的相互通信

在Android开发中,有时候我们需要让一个Activity绑定一个Service,进行两者之间的通信.当Activity绑定成功以后,就可以调用Service中的public(或有对应可见级别)的方法.如果Service想把一些信息反馈给Activity,则需要将Activity的Listener传递给Service,由Service负责调用. 这样的做法是可以实现功能的,但有一些缺憾. 首先,Service需要把被调用的方法做成public的,不利于隐藏实现. 第二,调用显得凌乱,在Acti

activity与service进程内通信

package com.example.binbin.testbinder; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; import android.widget.Toast; /

Activity和Service之间只相差了一个Window

从使用的角度来说: - Activity主要处理需要用户参与的任务 - Service主要后台处理一些不需要用户参与的任务 从实现角度来看,是什么造成了它们之间的区别,我很好奇的翻了翻源码,发现: Activity和Service 都是由共同的祖先派生下来的,其实Activty和Service之间最大的区别是 Activity包含了一个Window,但是Service没有. 那么Window是如何和Activity勾搭上的呢? 1. Activity里面所有的View都是放在Window里面管理

Activity与Fragment之间的通信

有时候我们需要在fragment与Activity之间通信,下面简单的总结下. 首先贴一个结果吧.在输入框中输入信息-->按钮-->弹出消息toast 分两部分: Activity——>Fragment 在Activity中创建Bundle数据包,并且调用Fragment的setArguments(Bundle bundle). FragmentActivity.java fragment.java  Fragment——>Activity 需要在Fragment中定义一个内部回调

Aactivity和Service之间的通信

一.在activity中定义三个按钮 一个开启服务  一个关闭服务,还有一个是向服务发送广播 当创建出Serevice时先执行Service的onCreate()创建服务后只执行一次 以后每次点击开启服务都不会再执行onCreate()而是去执行onStartCommand()停止服务时执行Service的onDestroy() 二.在Activity中点击发送广播键会向服务发送广播(本例采用LocalBroadcastManager发送和接受广播)服务接收广播吐司出“接收到activity的广

Android基础笔记(十一)- Service基础和注意事项以及Activity与Service的通信

Service的基本概念 为什么要有Service Service的基本用法 电话窃听器的小案例 Service和Activity通信 Service和Thread的关系 向光明而行! Service的基本概念 Service是Android的四大组件之一,在每一个应用程序中都扮演者非常重要的角色. 它主要用于在后台处理一些耗时的逻辑,或者去执行某些需要长期运行的任务.必要的时候,我们甚至可以在程序退出的情况下,让Service在后台继续保持运行状态. 既然都是被用于处理耗时的操作,那么我们什么

Android四大组件应用系列——Activity与Service交互实现APK下载

Servic与Activity相比它没有界面,主要是在后台执行一些任务,Service有两种启动方法startService()和bindService(),startService方式Service不可交互,可一直在后台即便应用结束,bindService方式可通过ServiceConnection获得运行的Service实例的方式实现Activity和Service之间的交互,通常Activity退出则绑定的服务也就取消了.我们可以通过同时执行启动服务和绑定服务的方式实现Service交互同

使用Broadcast实现android组件之间的通信

android组件之间的通信有多种实现方式.Broadcast就是当中一种. 在activity和fragment之间的通信,broadcast用的很多其它本文以一个activity为例. 效果如图: 布局文件: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" andro

android activity和service的交互介绍

android开发中,作为4大组件的service在开发中经常会使用到.很多时候,我们的activity和service之间需要进行相应的交互,activity需要调用service里面的方法实现某些功能,service需要调用activity的方法,实现界面更新等的交互. 实现2者之间相互交互的主要方式是:service中有个类部类继承Binder,然后提供一个公有方法,返回当前service的实例. activity通过bindService来开启一个service,service通过onB