Android Service学习心得总结

学习了郭大神关于Service的讲解,顿时醍醐灌顶,豁然开朗,对Service有了更深层的理解,趁热打铁把所学的知识记录下来,也算是一种复习加深记忆的好办法。

开发环境:Android Studio 2.3.3

一、Service的基础知识

Service是Android四大组件之一,主要用于在后台处理一些比较费时间的任务,也可用于前台处理,比如天气的显示在StatusBar中。

Service特点:

  • 主要用于后台,处理一些耗时任务或长期运行的任务;
  • Service运行在主线程中,所以在Service中无法执行非常耗时的任务,否则出现ANR;
  • 在程序退出后,Service也可以保持运行状态;

1.创建Service

新建一个工程FirstService,工程中创建文件:MainAcitvity.java,FirstService.java,activity_main.xml,具体代码在本文最后;

MainAcitivity.java:主Activity,启动、绑定服务,调用服务中的方法;Client端

FirstService:实现Service,实现要调用的方法;Service端

activity_main.xml:布局文件。

2.Service与Activity的通信:OnBind

FirstService.java: OnBind()是Service中的一个成员函数,主要作用是将Service和Activity连接在一起

    public MyBinder myBinder=new MyBinder();

    public FirstService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG,"FirstService onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG,"FirstService onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.d(TAG,"FirstService onDestroy");
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return myBinder;//返回MyBinder对象,在client端调用bindService()时会调用onBind()
    }

    public class MyBinder extends Binder{
        int add(int num1,int num2){
            return num1+num2;
        }
    }

绑定服务:Client:MainAcitivity.java

                Intent bindintent=new Intent(this,FirstService.class);
                bindService(bindintent,connection,BIND_AUTO_CREATE);//connection是Service对象

private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.d(TAG,"onServiceConnected1");
            binder=(FirstService.MyBinder)iBinder;
            Log.d(TAG,"onServiceConnected2");
            int ret=binder.add(50,50);
            Log.d(TAG,"ret ="+ret);
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };

3.前台服务:Service大部分都是在后台运行,但是由于Service的系统优先级是比较低的,所以当系统出现内存不足时,系统为了保证一些优先级高的程序能运行,会杀掉一些优先级低的程序或内存来释放资源。如果你想让你的Service优先级提高,可以用setForeground(true)来改变优先级。Service默认被标记为background,当前运行的Acitivity一般被标记为foreground。但这也并不能保证Services用于不会被杀掉,只是提高了优先级。

下面举例说明如何将一个实现一个前台服务:

FirstService.java:onCreate()

@Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG,"FirstService onCreate");
        Intent notificationIntent=new Intent(this,MainActivity.class);
        PendingIntent pendingIntent= PendingIntent.getActivity(this,0,notificationIntent,0);
        Notification notification=new Notification.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("This is a notification")
                .setColor(0xffff)
                .setContentIntent(pendingIntent)
                .build();
        startForeground(1,notification);//提高服务的优先级
    }
在client端调用startService()后,调到FirstService的onCreate(),前台服务启动。

4.Service 与AIDL

  • 进程间通信(IPC)1

定义aidl.java文件:在main/目录下定义IMyAidlInterface.aidl文件


然后Build-->Make Project,系统会生成一个.aidl文件。


在AndroidManifest.xml文件中,加入 android:process=":remote",Service将运行在:remote进程中

<service
            android:name=".FirstService"
            android:enabled="true"
            android:exported="true"
            android:process=":remote">
        </service>


在IMyAidlInterface中定义方法:

interface IMyAidlInterface {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    int Del(int num1,int num2);
}
在FirstService.java中,定义一个IMyAidlInterface.Stub对象binder并实现接口中的方法,在onBinder()中返回binder;

IMyAidlInterface.Stub binder=new IMyAidlInterface.Stub() {
        @Override
        public int Del(int num1, int num2) throws RemoteException {

            return num1-num2;
        }
    };
在Client端Maintivity.java中调用,其他的都和之前一样,在定义ServiceConnection对象connection的onServiceConnected()函数中调用;

private IMyAidlInterface myAidlInterface;//定义一个IMyAidlInterface对象

private ServiceConnection connection = new ServiceConnection() {

        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            myAidlInterface=IMyAidlInterface.Stub.asInterface(iBinder);//

            //binder=(FirstService.MyBinder)iBinder;
            try {
                int ret = myAidlInterface.Del(10,2);//调用方法

  
  
  • };
Log.d(TAG,"ret ="+ret); } catch (RemoteException e) { e.printStackTrace(); } //int ret=binder.add(50,50); } @Override public void onServiceDisconnected(ComponentName componentName) { }
这样就可以调用aidl中的方法。
  • 进程间通信--2 远程调用Service
服务端:FirstService

在AndroidManifest.xml:

<service
            android:name=".FirstService"
            android:enabled="true"
            android:exported="true"
            android:process=":remote">
            <intent-filter>
                <action android:name="qumy.com.firstservice.IMyAidlInterface"/>//
            </intent-filter>
        </service>

客户端:FirstClient:

新建项目:FirstClient,将服务端src/main目录下的aidl文件夹直接拷贝到FirstClient工程中的src/main目录下如下图,


点击Build-->Make Project,生成的文件IMyAidlInterface.java如下图目录:


在activity_main.xml中定义一个Button,用于绑定Serivce;

在MainActivity.java中:

private Button bindservice;
bindservice=(Button)findViewById(R.id.bindService);
        bindservice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent();//新建一个Intent
                intent.setPackage("qumy.com.firstservice");
                intent.setAction("qumy.com.firstservice.IMyAidlInterface");//设置Action
                bindService(intent,connection,BIND_AUTO_CREATE);

            }
        });
connection的定义:

private IMyAidlInterface imyaidlInterface;//定义一个IMyAidlInterface对象

    ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            imyaidlInterface=IMyAidlInterface.Stub.asInterface(iBinder);//asInterface返回一个IMyAidlInterface对象
            try {
                int ret=imyaidlInterface.Del(20,10);//调用Service端的方法Del();
                Log.d(TAG,"ret="+ret);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };

这样就实现了远程调用Service的功能。

Service是Android非常重要的组件,本次的学习记录仍有不足之处,在以后的学习中会慢慢深入,感谢阅读,共同进步。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android开发中,Service是一个非常重要的组件,用于在后台执行长时间运行的操作,不与用户交互。以下是本次实验总结: 1. Service生命周期 Service的生命周期包括:onCreate()、onStartCommand()、onBind()、onUnbind()、onRebind()和onDestroy()。开发者可以根据不同的业务需求实现这些生命周期函数。 2. Service的启动和停止 Service的启动和停止有两种方式:使用startService()和stopService()方法来启动和停止Service;使用bindService()和unbindService()方法来绑定和解绑Service。需要注意的是,使用startService()方法启动的Service会一直运行,直到调用stopService()方法或者Service自己调用stopSelf()方法;使用bindService()方法启动的Service会在与之绑定的Activity销毁时自动停止。 3. Service的通信 Service可以和Activity之间进行通信,可以使用Intent传递数据,也可以使用Messenger进行通信。如果需要在Service中执行耗时操作,需要在Service中开启一个新的线程来执行,否则会阻塞主线程。 4. Service的注册 在AndroidManifest.xml文件中注册Service,可以使用以下代码: ``` <service android:name=".MyService" /> ``` 5. Service的注意事项 在使用Service时,需要注意以下几点: - Service是在主线程中运行的,不能在Service中执行耗时操作,否则会阻塞主线程。 - Service一旦启动就会一直运行,需要在适当的时候停止Service。 - Service可以和Activity之间进行通信,需要根据具体的业务需求选择合适的通信方式。 总之,ServiceAndroid开发中非常重要的组件,掌握其使用方法和生命周期函数对于开发高质量的Android应用程序非常有帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值