如何写一个android服务

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;
		}
	}

	@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);



你可能感兴趣的:(android,service,服务,前台服务)