• android Service学习


      ->通过显示启动的服务
        1.创建一个Service需要继承Service

    public class Myservice extends Service

        2.并在AndroidManifest 中声明<service/>,如果不声明的话,会报错   

            <service
                android:name=".Myservice"  ></service>


        3.在Activity 中就可以调用startService()方法来启动服务
          需要传的是一个Intent()
          停止的方法是StopService(Intent);

      intent=new Intent(this,Myservice.class);
    startService(intent);

        4.通过startService启动的服务的声明周期大概如下
          onCreate()->onStartComment()->onDestroy()
          在这里需要注意的是Service只创建一次
      ->通过绑定启动的服务
        调用bindService(Intent,ServiceConnection,flage);方法来绑定的  

    intent=new Intent(this,Myservice.class);
    bindService(intent, this, Context.BIND_AUTO_CREATE);

      由于是动态绑定的Service,那么我们什么时候知道他已经启动和停止了呢?

        所以我们需要实现 ServiceConnection 这个接口

          下面是需要实现的两个方法

          public void onServiceConnected(ComponentName arg0, IBinder arg1) 从字面上理解就是已经连接后

            那么问题来了,这两个方法有什么用处?也就是它们存在的意义是什么?,你们可能已经注意到了,

              这里有一个IBinder 对象

          public void onServiceDisconnected(ComponentName arg0) 关闭连接后

        

      生命周期如下
          onCreate()->onBind()->onServiceConnected()->onDestroy();
          当然这个Service的生命周期还是和绑定的Activity向关联的,也就是说如果Activity被销毁,则Service也被销毁
      ->互相传参数
        1.通过bundle  

                intent.putExtra("data",edi.getText().toString());
                startService(intent);

        2.通过Binder(只适用于,通过绑定来启动的服务)

          实现过程如下:

          1.实现方法  

        @Override
        public IBinder onBind(Intent arg0) {
          return null;
        }

          2.既然上面需要一个实现了IBinder的接口类,那么我们就创建它,也就是用它来传递数据

        

    private String Data="我是默认的数据";
    public
    class MyBinder extends Binder {
      
    public void Setdata(String s) { Data=s; } }

        3.然后我们就通过onBind->return new MyBinder();

        4.既然我们已经成功的发送数据出去了,那我们怎么在外部获取呢?

          在这里需要强调一下它的生命周期

            onCreate()->onBind()->onServiceConnected()->onDestroy()

          从上面可以看到,onServiceConnected(),是在onBind()之后调用的,而且

        

    public void onServiceConnected(ComponentName arg0, IBinder arg1)

         所以我们就可以拿到数据了


        3.通过回调->这种方法在任何时候都是可以用的,

          实现代码如下

          首先,需要声明一个接口

    private Callback callback=null;
    public
    static interface Callback{ void SetText(String s); }

        然后,需要将这个接口传递给需要实现的那个类里面,然后重写方法,就可以了

        当然,在服务的线程中是不可以操作,主线程的UI的,所以需要有中间者Handler来进行处理,

    下面贴,实现的全部代码:

    package com.example.service;
    
    import android.app.Activity;
    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.content.ServiceConnection;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.IBinder;
    import android.os.Message;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.EditText;
    
    import com.example.service.Myservice.Callback;
    import com.example.service.Myservice.MyBinder;
    
    
    public class MainActivity extends Activity implements OnClickListener,ServiceConnection {
    private Intent intent;
    private EditText edi;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            intent=new Intent(this,Myservice.class);
            edi=(EditText)findViewById(R.id.ediText);
            findViewById(R.id.btnStart).setOnClickListener(this);
            findViewById(R.id.btnStop).setOnClickListener(this);
            findViewById(R.id.btnBind).setOnClickListener(this);
            findViewById(R.id.btnUnBind).setOnClickListener(this);
            findViewById(R.id.btnSendText).setOnClickListener(this);
        }
    
        @Override
        public void onClick(View arg0) {
            switch(arg0.getId())
            {
            case R.id.btnStart:
                intent.putExtra("data",edi.getText().toString());
                startService(intent);
                break;
            case R.id.btnStop:
                stopService(intent);
                break;
            case R.id.btnBind:
                bindService(intent, this, Context.BIND_AUTO_CREATE);
                break;
            case R.id.btnUnBind:
                unbindService(this);
                break;
                
            }
            
        }
    
        @Override
        public void onServiceConnected(ComponentName arg0, IBinder arg1) {
            // TODO Auto-generated method stub
            Log.i("test", "onServiceConnected");
        MyBinder b=(MyBinder)arg1;
        b.Setdata("111111111111");
        b.GetCallback().setCallback(new Callback() {
            
            @Override
            public void SetText(String s) {
                Message me=new Message();
                Bundle b=new Bundle();
                b.putString("data",s);
                me.setData(b);
                handler.sendMessage(me);
                
            }
        });
            
        }
        private Handler handler=new Handler(){
    
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
                Bundle b=msg.getData();
            String s=b.getString("data");
            edi.setText(s);
                
            }
            
            
            
        };
    
        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            // TODO Auto-generated method stub
            
        }
    
    }

    package com.example.service;
    
    import android.app.Service;
    import android.content.Intent;
    import android.os.Binder;
    import android.os.IBinder;
    import android.util.Log;
    
    public class Myservice extends Service {
    private String Data="我是默认的数据";
    private boolean running=false;
        @Override
        public IBinder onBind(Intent arg0) {
            Log.i("test", "onBind");
            return new MyBinder();
        }
    public class MyBinder extends Binder
    {
        public void Setdata(String s)
        {
        Data=s;
        }
        public Myservice GetCallback()
        {
            return Myservice.this;
        }
    }    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.i("test", "onstartCommand");
            Data=intent.getStringExtra("data");
            return super.onStartCommand(intent, flags, startId);
        }
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        new Thread(){
    
            @Override
            public void run() {
                running=true;
                super.run();
                while(running)
                {
                    //System.out.println(Data);
                    if(callback!=null)
                        callback.SetText(Data);
                        //Log.i("test",Data);
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        Log.i("test", "发生错误");
                        e.printStackTrace();
                    }
                }
            }
             
        }.start();
        Log.i("test", "onCrate");
    }
    @Override
    public void onDestroy() {
        running=false;
        super.onDestroy();
        Log.i("test", "onDestroy");
    }
    private Callback callback=null;
    
    public Callback getCallback() {
        return callback;
    }
    public void setCallback(Callback callback) {
        this.callback = callback;
    }
    public static interface Callback{
        void SetText(String s);
    }
    
    
    }

    <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:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.example.service.MainActivity" 
        android:orientation="vertical"
        >
    <EditText 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ediText"
        android:text="ddddddddddddd"
        />
        <Button
            android:id="@+id/btnStart"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="开启服务" />
    
        <Button
            android:id="@+id/btnStop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="关闭服务" />
    
        <Button
            android:id="@+id/btnBind"
            android:layout_width="94dp"
            android:layout_height="wrap_content"
            android:text="绑定服务" />
    
        <Button
            android:id="@+id/btnUnBind"
            android:layout_width="96dp"
            android:layout_height="wrap_content"
            android:text="解除绑定" />
    
        <Button
            android:id="@+id/btnSendText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="改变数据" />
    
    </LinearLayout>

    ->跨应用启动服务,
    只需要在Intent中设置setComponent(包名,组件名称);
    跨应用通讯,需要实现iadl

    Hold on, everything is possible.
  • 相关阅读:
    HTML5 ④
    HTML5 ③
    HTML5 ②
    HTML5 ①
    what’s this?
    第一篇
    2017年3月1号课堂笔记
    2017年2月27号课堂笔记
    2017年2月24号课堂笔记
    2017.02.15课堂笔记
  • 原文地址:https://www.cnblogs.com/student-note/p/6118199.html
Copyright © 2020-2023  润新知