浅谈Service

来源:互联网 发布:天干地支算法 编辑:程序博客网 时间:2024/05/29 19:47

接触Android有一段时间了,今天就来讲讲我对Service的理解吧(PS:有理解错误的希望大家说出来哦~~)

Service 作为四大组件之一,在每个应用程序中都起着重要的作用,一半是在后台处理一些耗时的逻辑,有时候我们要退出应用程序的时候,可以让Service 在后台继续运作。

关于Service 的用法,就是如何启动Service 。启动Service 有两种模式:startService和bindService

这两种模式又分别有不同的生命周期方法:

startService :启动模式的Service 需要调用Context的startService方法启动,并且可以调用context对象的stopService停止service ,当然,例如我们希望在service 内部停止service 可以调用stopSelf()。

bindService : Service的绑定模式相当于activity和service之间建立了一个长连接(ServiceConnection),在activity中可以借助此连接对象操作service中的方法。Service 的绑定模式要借助 context 的 bindService 实现绑定,借助 unBindService 解除绑定。

这里写图片描述
这里写图片描述

这个Demo是BroadcastReceiver与Service 相结合。

发广播

            Intent intent=new Intent("BroadcastRevices");            String numberStr = number.getText().toString().trim();            System.out.println("number:"+numberStr);            intent.putExtra("name", numberStr);            MainActivity.this.sendBroadcast(intent);

收到广播

public class BroadcastRevices extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        if(intent.getAction().equals("BroadcastRevices")){            System.out.println("收到广播服务,启动Service");            Intent mIntent=new Intent(MainActivity.instance,ServiceDemo.class);            mIntent.putExtra("name", intent.getStringExtra("name"));            context.startService(mIntent);        }    }}

收到广播启动服务

private void senMessage(String number) {        System.out.println("number:"+number);        //启动service        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);        //创建消息栏        Notification notification = new Notification.Builder(MainActivity.instance)                .setTicker(number)                .setContentText(number)                .setContentTitle(number)                .setSmallIcon(R.drawable.ic_launcher)                .build();        Intent intent=new Intent(this,SecondActivity.class);        intent.putExtra("number",number );        //消息栏的焦点,PendingIntent.FLAG_UPDATE_CURRENT覆盖前一条信息的内容        notification.contentIntent=PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);        //启动notification        manager.notify(R.drawable.ic_launcher, notification);    }

服务启动发消息

public int onStartCommand(Intent intent, int flags, int startId) {        //传值        String number = intent.getStringExtra("name");        System.out.println("服务已启动开始发送消息通知:"+number);        senMessage(number);        return super.onStartCommand(intent, flags, startId);    }
0 0