1.android服務簡介html
android服務的分類仍是蠻多的,網上有現成的博客講解的很好,我就不重複了,鏈接以下:java
http://www.cnblogs.com/newcj/archive/2011/05/30/2061370.html
android
本文主要介紹一種常見的服務:通知欄有圖標和文字的服務,既能夠作本身的事情,也能夠供其餘activity調用,專業術語描述爲 前臺服務(可startService也能夠bindService)app
2.原理和流程jsp
3.MyService.javaide
/** * @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; } } @Override public void onCreate() { Thread thr = new Thread(null, new ServiceWorker(), "BackgroundSercie"); thr.start(); super.onCreate(); } @Override public IBinder onBind(Intent intent) { Log.d(TAG, String.format("on bind,intent = %s", intent.toString())); notificationMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); displayNotificationMessage("服務已啓動"); return binder; } @Override public 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); } @Override public 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() { @Override public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub } @Override public 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);