Service介绍

2017-03-02  本文已影响14人  金馆长说

Service是Android中的四大组件之一它没用界面展示它运行在后台,它的作用是可以在程序启动后开启一个服务运行在后台做数据操作,
比较典型的就是音乐。service的运行线程和main线程一样都是同一个线程,一般来说我们使用service来操作耗时操作时候,需要去开启一个
新线程来处理,不然就是ARN异常,使用service需要在清单文件中配置好service。

生命周期

二种启动方式

public class TestSerice extends Service {
    private MyBind mMyBind = new MyBind();


    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("jinwei", "onCreate运行服务");
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("jinwei", "销毁服务");
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("jinwei", "onStartCommand服务");
        return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.i("jinwei", "onStart服务");
    }


    @Override
    public boolean onUnbind(Intent intent) {
        Log.i("jinwei", "onUnbind服务");
        return super.onUnbind(intent);
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("jinwei", "onBind服务");
        return mMyBind;
    }


    class MyBind extends Binder {
        public void startDownload() {
            Log.i("jinwei", "startDownload");
        }
    }


bundService用的连接对象,onServiceConnected里面可以获取的Bind,获得bind就可以操作service里面提供的一些方法了。
ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("jinweilog", "onServiceConnected" + name);
            mMyBind = (TestSerice.MyBind) service;
        }


        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("jinweilog", "onServiceDisconnected");
        }
    };



前台Service

服务器几乎全部都是在后台运行,服务器的系统优先级还是比较低的。如果说系统当前的内存较低的时候,后台这些服务器就可能会被系统回收掉。前台Service可以在通知栏启动一个常驻的栏目,这样做可以大大提高服务的系统优先级已达到不被系统回收,当然有时候我们也不能光是为了不让服务器被回收而去通知栏常驻一个栏目,这样会大大降低用户的体验。但是有些情况可能会需要使用到这样场景,比较一些天气和音乐播放器就需要一直在前台进行播放和数据采集,这种场景情况下就可以考虑使用常驻的前台Service来解决。

public void onCreate() {
        super.onCreate();
        com.jin.mak.Log.LogI("create");
        onCreateIntent();
    }


    private void onCreateIntent() {
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        Notification n = new NotificationCompat.Builder(this)
        .setContentTitle("This is title")
        .setContentText("This is Content")
        .setWhen(System.currentTimeMillis())
                .setContentIntent(pendingIntent)
        .setSmallIcon(R.drawable.ic_launcher_background).build();
        startForeground(1, n);
    }

自己需要在onCreate里面加入了一个startForeground的逻辑,就可以在通知栏上面看到我们的前台进程了。

参考

IntentService是Service的一个子类,里面有一个looper队列来处理Intent的请求,就是比一般的serivce多了一个处理队列的功能。

上一篇 下一篇

猜你喜欢

热点阅读