码迷,mamicode.com
首页 > 移动开发 > 详细

Android基础 ————四大组件之Service

时间:2016-04-13 01:54:34      阅读:276      评论:0      收藏:0      [点我收藏+]

标签:

public abstract class Service

OverView:

  A service is an application component representing either an application‘s desire to perform a long-running operation while not interacting with user or to supply functionality for other applications to use.Each service class must have a corresponding <service> declaration in its package‘s AndroidManifest.xml. Services can be started with Context.startService() and Context.bindService().

 

    一个服务是一个应用组件,这个组件可以在没有和用户进行交互的情况下执行长时间的操作,如(后台KuGou播放音乐)或为其他应用提供功能。每一个服务都应该在所在包中的AndroidManifest文件中注册<service></service>  在 Activity中,服务可以被Cotext.startService()开启,或Context.bindService()开启。

 

LifeCycle :

  There are two reasons that a service can be run by the system. If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client. The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their stopSelf(int) method to ensure the service is not stopped until started intents have been processed.

 

  服务的生命周期: 线程的执行有两种方式。如果一个组件调用了Context.startService()方法,系统会检索服务,(即首先调用服务的OnCreate()方法创建服务,然后调用onStartCommand(Intent,int,int)方法开启服务。)  一直到stopService()服务停止。需要注意的是,多次调用时,OnCreate只调用了一次。


Case 0 : TelePhoneListener
 1 package com.itheima.phonelistener;
 2 
 3 import java.io.IOException;
 4 
 5 import android.app.Service;
 6 import android.content.Context;
 7 import android.content.Intent;
 8 import android.media.MediaRecorder;
 9 import android.os.IBinder;
10 import android.telephony.PhoneStateListener;
11 import android.telephony.TelephonyManager;
12 
13 public class PhoneListenerService extends Service {
14 
15     @Override
16     public IBinder onBind(Intent intent) {
17         // TODO Auto-generated method stub
18         return null;
19     }
20 
21 
22     @Override
23     public void onCreate() {
24         super.onCreate();
25 
26         //监听电话到来
27 
28         //1.获取一个TelephonyManager对象
29         TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
30         //2.调用listener方法,注册一个电话状态改变的监听器   events:一个事件标记
31         telephonyManager.listen(new MyPhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE);
32 
33     }
34 
35     //监听电话状态改变的监听器类
36     class MyPhoneStateListener extends PhoneStateListener{
37         private MediaRecorder recorder;
38         @Override
39         public void onCallStateChanged(int state, String incomingNumber) {
40             super.onCallStateChanged(state, incomingNumber);
41             //一旦手机电话状态改变该方法将会执行
42             switch (state) {
43             case TelephonyManager.CALL_STATE_IDLE:// 空闲
44                 if(recorder != null){
45                     //停止录音,重置
46                     recorder.stop();
47                     recorder.reset();   // You can reuse the object by going back to setAudioSource() step
48                     recorder.release(); // Now the object cannot be reused
49                 }
50                 break;
51             case TelephonyManager.CALL_STATE_RINGING:// 响铃
52                 //创建对象
53                 recorder = new MediaRecorder();
54                 //设置音频来源,来自麦克风
55                 recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
56                 //设置输出格式
57                 recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
58                 //设置音频编码
59                 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
60                 //设置输出路径
61                 recorder.setOutputFile("/sdcard/luyin.3gp");
62                 try {
63                     recorder.prepare();
64                 } catch (IllegalStateException e) {
65                     e.printStackTrace();
66                 } catch (IOException e) {
67                     // TODO Auto-generated catch block
68                     e.printStackTrace();
69                 }
70                 break;
71 
72             case TelephonyManager.CALL_STATE_OFFHOOK:// 摘机
73                 if(recorder !=null){
74                     recorder.start();   // Recording is now started
75                 }
76                 break;
77             default:
78                 break;
79             }
80         }
81 
82     }
83 
84 
85 }

 

bindService():

  Clients can also use Context.bindService() to obtain a persistent connection to a service. This likewise creates the service if it is not already running (calling onCreate() while doing so), but does not call onStartCommand(). The client will receive the IBinder object that the service returns from its onBind(Intent) method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the service‘s IBinder). Usually the IBinder returned is for a complex interface that has been written in aidl.

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service‘s onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy(). 

 
bind方式开启服务:
  1) 第一次开启会调用onCreate()方法和onBind()方法,注意,并没有调用onStartCommand方法。
  2)bind方式开启的服务是一种隐性的服务,在设置--服务中是找不到的
  3)bind方式开启的服务生命周期依赖于开启者,与开启者不求同生,但求同死。
  4)开启者销毁是注意一定要解绑! unbindService(connection)
  5)只能解绑一次。
 
Case 1 : bind方式开启服务。

定义Iservice接口,提供Service方法调用
 
package com.itheima.whybind;

public interface Iservice {

    public void callBanzheng(int money);
    public void callDamajiang();
    public void callxisangna();
    
}

 

Service中提供了很多方法,但是不能被Activity调用,需要一个中间人MyBinder(onBind的返回类型),这个类继承Binder,并且实现Iservice接口,在Activity中则是通过

这个中间人调用Service的方法的。

package com.itheima.whybind;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;

public class WhyBinderService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("onBind");
        //就是中间人对象
        return new MyBinder();
    }

    
    //定义一个中间人的类,将服务中的办证方法暴漏出去
    class MyBinder extends Binder implements Iservice{

        @Override
        public void callBanzheng(int money) {
            banzheng(money);
        }

        @Override
        public void callDamajiang() {
            damajiang();
        }

        @Override
        public void callxisangna() {
            xisangna();
        }
        
        
        
        
    }
    
    public void  damajiang(){
        Toast.makeText(getApplicationContext(), "陪你打麻将", 0).show();
    }
    
    public void  xisangna(){
        Toast.makeText(getApplicationContext(), "陪你洗桑拿", 0).show();
    }
    
    
    public void banzheng(int money) {
        if(money >100){
            Context context2 = this;
            System.out.println(" getApplicationContext():"+ getApplicationContext());
            Context context = getApplicationContext();
            System.out.println("context2:"+context2);
            Toast.makeText(context, "证办好了", 0).show();
        }else{
            Toast.makeText(getApplicationContext(), "钱太少了", 0).show();
        }
    }
    
    @Override
    public void onCreate() {
        System.out.println("onCreate");
        super.onCreate();
    }
    

    
    @Override
    public void onDestroy() {
        System.out.println("onDestroy");
        super.onDestroy();
    }
}

Activity  

package com.itheima.whybind;

import com.itheima.whybind.WhyBinderService.MyBinder;

import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {

    private MyServiceConnection connection;


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

    //bind方式开启服务点击事件
    public void start(View v){

        Intent intent = new Intent(this,WhyBinderService.class);
        connection = new MyServiceConnection();
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    //办证方法点击事件点击事件
    public void banzheng(View v){
        //通过中间人对象调用服务中的方法
        myBinder.callBanzheng(200);
        myBinder.callxisangna();
        myBinder.callDamajiang();
    }

    //中间人对象
    private MyBinder myBinder;
    class MyServiceConnection implements ServiceConnection{
        //当开启的服务的onBinder方法有返回中间人对象时调用  name:组件的名称    service:中间人对象
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("onServiceConnected:"+name.toString());
            //Activity接受中间人对象,并强转成我们在服务中定义的那个中间人类的类型
            myBinder = (MyBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("onServiceDisconnected");
        }


    }


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





}

 

Android基础 ————四大组件之Service

标签:

原文地址:http://www.cnblogs.com/fanjianan/p/5385116.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!