Android 四大组件之一:Service 后台运行

来源:互联网 发布:iphone移动数据怎么关 编辑:程序博客网 时间:2024/04/30 05:04

一、Service介绍

  Service是Android四大组件中与Activity最相似的组件,它们都代表可执行的程序,Service与Activity的区别在于:Activity拥有用户界面,用于更换界面操作;Service没有用户界面,运行于后台服务,一般不会挂掉,可以进行耗时操作。Service具有完整的自己的生命周期。

二、Service的使用

Service的使用的使用分为两种方式,一种是Start方式,一种是Bind方式。

1、Start方式

  Service的使用方式非常简单,跟Activity用法差不多,都是需要一个继承他的class,再在manifest中进行配置,具体步骤如下。
1、定义继承Service的class类
2、在manifest中配置Service

(1)继承Service的class

注意:需要重写onCreate()、 onStartCommand()、onDestroy()方法

package com.example.myservice;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;import android.widget.Toast;public class MyServices extends Service{    @Override    public IBinder onBind(Intent intent) {        // TODO Auto-generated method stub        return null;    }    @Override    public void onCreate() {        // TODO Auto-generated method stub        super.onCreate();        Log.d("输出", "Create");        Toast.makeText(getApplicationContext(), "Create", Toast.LENGTH_LONG).show();    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        // TODO Auto-generated method stub        Log.d("输出", "onStartCommand");        Toast.makeText(getApplicationContext(), "onStartCommand", Toast.LENGTH_LONG).show();        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        // TODO Auto-generated method stub        Log.d("输出", "onDestroy");        Toast.makeText(getApplicationContext(), "onDestroy", Toast.LENGTH_LONG).show();        super.onDestroy();    }}

(2)manifest中配置service

添加代码如下:

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

(3)主界面开启

@Override    public void onClick(View v) {        switch (v.getId()) {        case R.id.start:            Intent intent=new Intent(getApplicationContext(),MyServices.class);            startService(intent);            break;        case R.id.stop:            Intent intent1=new Intent(getApplicationContext(),MyServices.class);            stopService(intent1);            break;        default:            break;        }    }

效果:

我们可以看到Service的运行过程
这里写图片描述

2、Start方式+BroadCast小例子

思路:在MainActivity中开启服务,在服务中发送广播,在MainActivity中接收广播,通过progressbar滚动条查看进度。

布局中添加progressbar

设置样式为水平滚动条

  style="?android:attr/progressBarStyleHorizontal"
  <ProgressBar         style="?android:attr/progressBarStyleHorizontal"          android:id="@+id/progressbar"        android:layout_width="match_parent"        android:layout_height="wrap_content"      android:progress="50"        />

在service中发广播

package com.example.myservice;import android.app.Activity;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;import android.widget.Toast;public class MyServices extends Service{    @Override    public IBinder onBind(Intent intent) {        // TODO Auto-generated method stub        return null;    }    @Override    public void onCreate() {        // TODO Auto-generated method stub        super.onCreate();        Log.d("输出", "Create");        Toast.makeText(getApplicationContext(), "Create", Toast.LENGTH_LONG).show();    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        new Thread(new Runnable() {            @Override            public void run() {                int count=0;                while(true){                    if(count==100){                         //      Toast.makeText(getApplicationContext(), "已完成下载", Toast.LENGTH_LONG).show();                    Log.d("输出", "已完成下载");                    }else{                    count++;                    try {                        Thread.sleep(100);                    } catch (InterruptedException e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    }                    Intent intent=new Intent();                    intent.setAction(MainActivity.DOWNLOAD);                    intent.putExtra("count", count);                    sendBroadcast(intent);                }            }            }        }).start();//      Log.d("输出", "onStartCommand");//      Toast.makeText(getApplicationContext(), "onStartCommand", Toast.LENGTH_LONG).show();        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        // TODO Auto-generated method stub        Log.d("输出", "onDestroy");        Toast.makeText(getApplicationContext(), "onDestroy", Toast.LENGTH_LONG).show();        super.onDestroy();    }}

在MainActivity中接收广播

package com.example.myservice;import android.os.Bundle;import android.app.Activity;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ProgressBar;public class MainActivity extends Activity implements OnClickListener {    private Button mbtn_start;    private Button mbtn_stop;    private Button mbtn_download;    private ProgressBar mprogressbar;    private Myreceivce myrecevice;    public static final String DOWNLOAD="com.receiver.test";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mbtn_start = (Button) findViewById(R.id.start);        mbtn_stop = (Button) findViewById(R.id.stop);        mbtn_download=(Button) findViewById(R.id.bt_download);        mprogressbar=(ProgressBar) findViewById(R.id.progressbar);        mbtn_start.setOnClickListener(this);        mbtn_stop.setOnClickListener(this);        mbtn_download.setOnClickListener(this);        IntentFilter filter=new IntentFilter(DOWNLOAD);        myrecevice=new Myreceivce();        registerReceiver(myrecevice, filter);    }    @Override    public void onClick(View v) {        switch (v.getId()) {        case R.id.start:            Intent intent=new Intent(getApplicationContext(),MyServices.class);            startService(intent);            break;        case R.id.stop:            Intent intent1=new Intent(getApplicationContext(),MyServices.class);            stopService(intent1);            break;            case R.id.bt_download:                Intent intent2=new Intent(getApplicationContext(),MyServices.class);                    startService(intent2);                break;        default:            break;        }    }    class Myreceivce extends BroadcastReceiver{        @Override        public void onReceive(Context context, Intent intent) {            int  count=intent.getIntExtra("count",0);            mprogressbar.setProgress(count);        }    }    @Override    protected void onDestroy() {        super.onDestroy();        unregisterReceiver(myrecevice);    }}

效果图

这里写图片描述

代码注意点

1、在activity中绑定接收广播(继承BroadcastReceiver的class)
2、在activity中动态注册广播
3、不要忘记在activity中注销广播
4、manifest中注册服务
5、thread中不能Toast

2、Bind方式

1、通过Binder接口实例,返回一个ServiceConnection对象给
2、通过ServiceConnection对象的相关方法可以获得Service对象。

实例

1、继承Service类

需要在其中写一个继承Binder的class,在类中写一个可以返回Service的公共方法

package com.example.myservice;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.util.Log;public class Mybindservice extends Service{    public class MyBinder extends Binder{        public Mybindservice getMyService(){            return Mybindservice.this;                  }    }    @Override    public IBinder onBind(Intent intent) {        //返回一个Binder对象        return new MyBinder();    }    @Override    public void onCreate() {        super.onCreate();        Log.d("bind启动", "onCreate");    }    @Override    public void onDestroy() {        super.onDestroy();        Log.d("bind启动", "onDestroy");    }    @Override    public boolean onUnbind(Intent intent) {        Log.d("bind启动", "onUnbind");        return super.onUnbind(intent);    }}

2、Mainactivity:

    private Myreceivce myrecevice;    private Mybindservice service;    private ServiceConnection conn=new ServiceConnection() {        //当启动源与Service断开连接的时候会调用这个方法        //比如Service崩溃或者被强行杀死        @Override        public void onServiceDisconnected(ComponentName name) {            Log.d("断开服务", "onServiceDisconnected");        }        //当启动源与Service成功连接的时候会调用该方法        @Override        public void onServiceConnected(ComponentName name, IBinder binder) {            Log.d("连接服务", "onServiceConnected");            //获得服务            service=((MyBinder)binder).getMyService();        }    };
Intent intent4 = new Intent(getApplicationContext(),                    Mybindservice.class);            unbindService(conn);

3、别忘记在manifest中注册

4、过程

这里写图片描述

3、Start方式与Bind方式的区别

  它们两个最大的区别就是能否与activity通信,Start方式仅用于启动service,与访问者之间不存在多关联,无法获得服务对象,而Bind方式是与activity进行绑定的,可以用于与启动源的数据通信。

0 0
原创粉丝点击