DEMO1:在Activity里声明一个回调方法,当service完成任务后,调用这个回调方法。

首先,我们先继承service,来创建服务,代码如下:

 package com.example.service;

 import android.app.Service;
 import android.content.Intent;
 import android.os.Binder;
 import android.os.IBinder;
 import android.util.Log;
 import android.widget.Button;

 public class MyService extends Service {

     public static final String TAG = "MYSERVICE";

     @Override
     public void onCreate() {
         Log.i(TAG, "MyService-->onCreate");
         super.onCreate();
     }

     @Override
     public void onDestroy() {
         Log.i(TAG, "MyService-->onDestroy");
         super.onDestroy();
     }

     @Override
     public int onStartCommand(Intent intent, int flags, int startId) {
         Log.i(TAG, "MyService-->onStartCommand");
         return super.onStartCommand(intent, flags, startId);
     }
     private MyBinder binder = new MyBinder();

     public class MyBinder extends Binder implements ICalculator
     {
          public MyService getService()
          {
              return MyService.this;
          }

          @Override
          public int add(int x, int y) {
                 try {
                     Thread.sleep(10000);
                 } catch (InterruptedException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
                 return x + y;
          }
     }

     @Override
     public IBinder onBind(Intent arg0) {

         return binder;
     }

 }

其中,我定义了一个公共的接口

package com.example.service;

public interface ICalculator {
    int add(int x,int y);
}

主页面:MainActivity.java

package com.example.servicedemo;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.example.service.ICalculator;
import com.example.service.MyService;

/*
 * bindService(intent,conn,flag)
 * Service:onCreate()
 * Service:onBind()
 * Activity:onServiceConnected()
 */
public class MainActivity extends Activity implements OnClickListener {
    private Button btnStartSrv,btnStopSrv,btnBindSrv;

    private ICalculator ical;

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

        btnStartSrv = (Button)findViewById(R.id.btnStartSrv);
        btnStopSrv = (Button)findViewById(R.id.btnStopSrv);
        btnBindSrv = (Button)findViewById(R.id.btnBindSrv);

        btnStartSrv.setOnClickListener(this);
        btnStopSrv.setOnClickListener(this);
        btnBindSrv.setOnClickListener(this);

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

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

    @Override
    public void onClick(View view) {
        Intent service = new Intent(this, MyService.class);
        switch(view.getId())
        {
            case R.id.btnStartSrv:
            {

                startService(service);
                break;
            }
            case R.id.btnStopSrv:
            {
                stopService(service);
                break;
            }
            case R.id.btnBindSrv:
            {
                testSrv();
                Toast.makeText(this, "服务调用完了", 1).show();
                break;
            }
            default:
                break;
        }
    }

    ServiceConnection conn=new ServiceConnection(){

        @Override
        public void onServiceConnected(ComponentName arg0, IBinder service) {
            ical = (ICalculator) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {

        }
    };

    public void testSrv()
    {
        if(ical != null)
        {
            int x = ical.add(3, 5);
            Toast.makeText(this, String.valueOf(x), 1).show();
        }
    }

}

我故意在service里的方法,做了休眠10秒钟,当我们点击的BindSrv按钮时,过了10秒钟才弹出对话框,得到服务的运行结果。

所以,如果我在service中处理相对耗时的,就得在服务中另开一个线程。

转载请注明http://www.cnblogs.com/yushengbo,否则将追究版权责任!

淘宝(阿里百川)手机客户端开发日记第六篇 Service详解(四)的更多相关文章

  1. 淘宝(阿里百川)手机客户端开发日记第六篇 Service详解(六)

    Service和Thread的关系 不少初学者都可能会有这样的疑惑,Service和Thread到底有什么关系呢?什么时候应该用Service,什么时候又应该用Thread? 答案是Service和T ...

  2. 淘宝(阿里百川)手机客户端开发日记第六篇 Service详解(五)

    我们现在对上一节中的DEMO进行改进,在服务中开启线程来执行. package com.example.service; import android.app.Service; import andr ...

  3. 淘宝(阿里百川)手机客户端开发日记第六篇 Service详解(三)

    主题:Service与Activity交互通信 问题的引出:现在有个需求,如果我们有一个下载任务,下载时间耗时比较长,并且当下载完毕后,需要更新UI的内容,这时,service中的bindServic ...

  4. 淘宝(阿里百川)手机客户端开发日记第六篇 Service详解(二)

    DEMO1:当我们点击启动服务时和点击停止服务的时候,观察服务的运行状态,布局由于简单,只是两个普通的Button按钮,在此我只上截图. java代码部分 第一步:我们需要实现一个服务类,继承自ser ...

  5. 淘宝(阿里百川)手机客户端开发日记第六篇 Service详解(一)

    public abstract class Service; [API文档关于Service类的介绍] A Service is an application component representi ...

  6. 淘宝(阿里百川)手机客户端开发日记第七篇 Service,Handler和Thread

    现在我们已经已经知道android有Service,Handler和Thread这些内容了,但是我想应该还有很多人对此并不是很清楚他们之间的区别! (1)Service 是运行在后端的程序,不与UI直 ...

  7. 淘宝(阿里百川)手机客户端开发日记第十一篇 JSP+Servlet

    由于本人从事.net开发已有多年经验,今天由于工作需要,我只能学习下JSP+Servlet,至于java web提供了更好的开发框架MVC,现在由于时间关系,我只好用JSP+Servlet来搭建服务器 ...

  8. 淘宝(阿里百川)手机客户端开发日记第五篇 SharedPreferences使用详解

    我们知道,Android中数据存储技术由于如下几种 1 使用SharedPreferences存储数据 2 文件存储数据 3 SQLite数据库存储数据 4 使用ContentProvider存储数据 ...

  9. 淘宝(阿里百川)手机客户端开发日记第十篇 阿里百川服务器环境介绍之API文档的快速链接(四)

    个人感觉比较重要的快速链接: http://open.taobao.com/doc/detail.htm?id=102513 http://open.taobao.com/doc/detail.htm ...

随机推荐

  1. -webkit-overflow-scrolling:touch iosBug

    IOS8+  -webkit-overflow-scrolling:touch 会导致webview崩溃 解决方案 用js动态添加样式  比如: $("body").css(&qu ...

  2. Implementing SQL Server Row and Cell Level Security

    Problem I have SQL Server databases with top secret, secret and unclassified data.  How can we estab ...

  3. js的__proto__与propertype的关系

    经典的再也不能经典的一篇博客:http://www.cnblogs.com/snandy/archive/2012/09/01/2664134.html js中最propertype的一些方法的理解h ...

  4. 重构笔记---MEF框架(下)

    概述 上一篇介绍了MEF的一个很简单很基本的应用,实现了MEF框架并展示了MEF框架的一些基本的要求和设置,这些基础知识很重要,接下来我们分析一下如何扩展或增强MEF框架内容. 增强的Contract ...

  5. python 条件判断和循环

    一.条件判断    if if  age>= 18: 记住在判断语句后面要加上     : 还有要注意他的缩进 age = 20if age >= 18: print 'your age ...

  6. HTML5动画实例

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...

  7. MyEclipse 开发 Web项目发布到 Tomcat 下的Root 目录

    通常情况下,Web项目是发布到Tomcat下的webapps文件目录下的 . 例如:Web应用项目名称为:stock,则部署到tomcat后,是部署在tomcat/webapps/stock中,网址为 ...

  8. Java设计模式-解释器模式(Interpreter)

    解释器模式是我们暂时的最后一讲,一般主要应用在OOP开发中的编译器的开发中,所以适用面比较窄. Context类是一个上下文环境类,Plus和Minus分别是用来计算的实现,代码如下: public ...

  9. 图解Android - 如何看Android的UML 图?

    如何看UML图? UML能给我们带来什么? 这是本文要寻找的答案.UML图有很多类型,我们这里只讨论最重要也最常用的两种 - 类图和时序图. 1. 类图 通过类图,我们可以很容易的了解代码架构,理清模 ...

  10. 详解Java中ArrayList、Vector、LinkedList三者的异同点

    转载:https://my.oschina.net/zzw922cn/blog/491631 一.ArrayList ArrayList是一个可以处理变长数组的类型,这里不局限于"数&quo ...