加入收藏 | 设为首页 | 会员中心 | 我要投稿 应用网_丽江站长网 (http://www.0888zz.com/)- 科技、建站、数据工具、云上网络、机器学习!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

Android service 精辟介绍

发布时间:2021-12-18 16:58:47 所属栏目:PHP教程 来源:互联网
导读:本地服务 所谓本地服务,其实就是完全服务于一个进程的组件。本地服务的这种特性决定了它有特别的启动方式。通常这类服务的典型案例,就是邮件轮询。 调用Context.startService()启动服务 package net.bpsky; import Android.app.Notification; import andro

本地服务
 
所谓本地服务,其实就是完全服务于一个进程的组件。本地服务的这种特性决定了它有特别的启动方式。通常这类服务的典型案例,就是邮件轮询。
 
调用Context.startService()启动服务
 
package net.bpsky;
 
import Android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
 
public class DoudingService extends Service {
     
    private NotificationManager notificationMgr;
 
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }
     
    @Override
    public void onCreate(){
        super.onCreate();
         
        notificationMgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        displayNotificationMessage("Starting Background Service!");
        Thread thr = new Thread(null,new ServiceWorker(),"BackgroundService");
        thr.start();
    }
     
    class ServiceWorker implements Runnable{
        public void run(){
            // bla bla bla...
        }
    }
     
    @Override
    public void onDestroy(){
        displayNotificationMessage("Stopping Background Service");
        super.onDestroy();
    }
     
    @Override
    public void  onStart(Intent intent,int startId){
        super.onStart(intent, startId);
    }
     
    private void displayNotificationMessage(String message){
        Notification notification = new Notification(R.drawable.note,message,System.currentTimeMillis());
        PendingIntent contentIntent = PendingIntent.getActivity(this,0,new Intent(this,FeedActivity.class),0);
        notification.setLatestEventInfo(this, "background Service", message, contentIntent);
        notificationMgr.notify(R.id.app_notification_id,notification);
    }
 
}
远程服务
支持onBind()方法的,就是远程服务。远程服务并不是说一定要远程访问,而是支持(RPC,Remote Procedure Call,远程过程调用)。这类服务的典型案例就是应用程序之间执行通信。比如:路由服务,将信息转发至其它应用程序。远程服务最重要的一个特性就是需要AIDL(Android Interface Definition Language)向客户端定义自身。
 
定义AIDL接口
调用Context.bindService()绑定调用
优势在于允许不同进程进行绑定调用
在使用bindService时是异步操作,目标服务如果未在后台运行,那么在链接过程中会被启动。
下面我们来作一个调用模拟,可以看到图例大概的结构是这样的。

(编辑:应用网_丽江站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读