如何写一个android服务

Android  /  houtizong 发布于 3年前   126

1.android服务简介

android服务的分类还是蛮多的,网上有现成的博客讲解的很好,我就不重复了,连接如下:

http://www.cnblogs.com/newcj/archive/2011/05/30/2061370.html

本文主要介绍一种常见的服务:通知栏有图标和文字的服务,既可以做自己的事情,也可以供其他activity调用,专业术语描述为 前台服务(可startService也可以bindService)


2.原理和流程

  • 要创建前台服务,我们只需要提供一个通知栏图标并且调用startForeground即可
  • 要让服务自己做自己的事情,很简单,在onCreate或者onStartCommand的时候起一个Thread即可
  • 想要和服务通信、调用服务提供的函数,只需要在onBind的时候返回一个IBinder对象,通过IBinder对象可以获取当前Service对象的引用,有了引用就可以调用服务提供的函数了。
  • 最后一条,服务要在xml里面配置
    <service android:name="com.scott.sayhi.MyService" >
    </service>

3.MyService.java

/** * @author scott * */public class MyService extends Service {private final static String TAG = "MyService";private NotificationManager notificationMgr;   private boolean canRun =true;private String retString = null;//用于和外界交互private final IBinder binder = new MyBinder();public class MyBinder extends Binder{MyService getService(){return MyService.this;}}@Overridepublic void onCreate(){Thread thr = new Thread(null, new ServiceWorker(), "BackgroundSercie");   thr.start();  super.onCreate();}@Overridepublic IBinder onBind(Intent intent){Log.d(TAG, String.format("on bind,intent = %s", intent.toString()));notificationMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);   displayNotificationMessage("服务已启动");   return binder;}@Overridepublic int onStartCommand(Intent intent, int flags, int startId){Log.d(TAG, "start action="+intent.getAction());notificationMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);   displayNotificationMessage("服务已启动", true);   return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy(){stopForeground(true);canRun = false;super.onDestroy();}public String getImage(String url){return "19";}public String getRetString(){return retString;}//loginValidate 为service提供给外部调用的函数public boolean loginValidate(String userName, String password) throws Exception{String uriString = "http://www.renyugang.cn/blog/admin/admin_check.jsp";boolean ret = false;Log.d("scott", "enter myservice start loginvalidate");try{DefaultHttpClient httpClient = new DefaultHttpClient();HttpResponse response;HttpPost httpPost = new HttpPost(uriString);List<NameValuePair> nvps = new ArrayList<NameValuePair>();nvps.add(new BasicNameValuePair("name", userName));nvps.add(new BasicNameValuePair("password", password));httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));response = httpClient.execute(httpPost);HttpEntity entity = response.getEntity();retString = EntityUtils.toString(entity);retString = str_Filter(retString);if (response.getStatusLine().getStatusCode() == 200){if(retString.equals("") == false){if (retString.startsWith("用户名") == true){ret = false;}else{ret = true;}Log.d("retcontent", retString);Log.d("info", userName+password);Log.d("ret", ""+ret);}}} catch (Exception e){throw e;}return ret;}public String str_Filter(String strSource){String strPattern = "(?i)(\r\n|\r|\n|\n\r)";strSource.trim();Pattern p = Pattern.compile(strPattern);Matcher m = p.matcher(strSource);if (m.find()) {strSource = strSource.replaceAll("(\r\n|\r|\n|\n\r)", "");}return strSource;}//为服务设置图标和文字描述private void displayNotificationMessage(String message, boolean isForeground){   Notification notification = new Notification(R.drawable.icon, message,   System.currentTimeMillis());   PendingIntent contentIntent = PendingIntent.getActivity(this, 0,   new Intent(this, MyActivity.class), 0);   notification.setLatestEventInfo(this, "My Service", message,   contentIntent);   MyService.this.startForeground(R.id.app_notification_id, notification);}   private void displayNotificationMessage(String message){   Notification notification = new Notification(R.drawable.icon, message,   System.currentTimeMillis());   PendingIntent contentIntent = PendingIntent.getActivity(this, 0,   new Intent(this, MyActivity.class), 0);   notification.setLatestEventInfo(this, "我的通知", message,   contentIntent);   notificationMgr.notify(R.id.app_notification_id + 1, notification);  }   //ServiceWorker service自身的线程,用于做自己的事情,这里为了表示服务的确在运行,每2秒打印一次log信息。class ServiceWorker implements Runnable{ int counter = 0;@Override  public void run() {   // do background processing here.....   while(canRun){Log.d("scott", ""+counter);counter ++;try{Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}}}   }   }

4.如何使用服务

private MyService mMyService;private ServiceConnection mServiceConnection = new ServiceConnection(){@Overridepublic void onServiceDisconnected(ComponentName name){// TODO Auto-generated method stub}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {// bindService成功的时候返回service的引用MyBinder myBinder = (MyBinder)service;mMyService = myBinder.getService();}}//启动服务Intent intentService = new Intent(MyActivity.this, MyService.class);intentService.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intentService.setAction("scott");//bindService用于和service进行交互MyActivity.this.bindService(intentService, mServiceConnection, BIND_AUTO_CREATE);//startService用于启动service但是不和其交互startService(intentService);



请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客