细谈编程语言建立的后台服务---my note

  就拿c#编程语言来讲吧: java


用c#中建立一个windows服务很是简单,与windows服务相关的类都在System.ServiceProcess命名空间下。 mysql

每一个服务都须要继承自ServiceBase类,并重写相应的启动、暂停、中止等方法。 android

windows服务的相关信息是存放与注册表中的,因此他能够在不须要用户登陆的状况下自动运行,在c#中你不须要再直接向注册表中添加信息了,c#提供了服务安装类 ServiceProcessInstaller和ServiceInstaller来实现服务的安装。 web

首先,用vs建立一个windows服务项目 sql


Program中只包含服务运行的相关信息 apache

代码以下:

/// <summary>
/// 应用程序的主入口点。
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()//这里是一个数组,意味着咱们能够在一个服务进程中建立多个服务实例,只须要在这里加上便可
};
ServiceBase.Run(ServicesToRun);
}

Service1.cs就是咱们须要的服务类,与windows服务相关的基本操做大均可以在这里找到,如:Start,Stop,Pause,Continue等,咱们要作的就是根据这些操做作不一样的处理就能够了。 编程

咱们先在服务Start和Stop时分别记录一条信息到D盘 c#

代码以下:

protected override void OnStart(string[] args)
{
File.AppendAllText("d:" + this.GetType().Name + ".txt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss 服务启动"));
}
protected override void OnStop()
{
File.AppendAllText("d:" + this.GetType().Name + ".txt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss 服务中止"));
}

一个简单的服务就完成了,下一步添加安装信息

双击项目中的Service.cs转到服务设计界面,在空白处右键选择“添加安装程序” windows


vs会自动建立一个默认名称为ProjectInstaller.cs的文件并转到相应的设计界面 数组

默认添加两个类 serviceProcessInstaller1和serviceInstaller1,第一个主要用来设置服务所属帐户,关系到服务的运行,第二个是服务信息描述,如:服务名、是否自动启动等

右键serviceProcessInstaller1属性,将Account属性选择为LocalSystem

因为windows服务不能经过双击直接运行,因此咱们须要借助.net提供的InstallUtil.exe来安装服务。

打开windows服务管理器就能看到咱们安装的服务,默认服务安装成功后不会马上启动,须要咱们手动启动。

android建立后台服务


Android中使用IntentService建立Android系统后台服务

IntentService提供了在单个后台线程运行操做的简单结构。这容许它操做耗时操做,而不影响UI响应。一样,IntentService也不影响UI生命周期事件,因此,它在某些可能关闭AsyncTask的状况下,仍会继续运行(实测在Activity的onDestory里写AsyncTask没法运行)。

IntentService有以下限制:

1.它不能直接影响UI。要把结果反映给UI,须要发给Activity
2.工做请求会顺序运行。若是一个操做未结束,后面发送的操做必须等它结束(单线程)
3.IntentService里运行的操做没法被中断

然而,在大多数状况下,IntentService是简单后台任务的首选方式。

本节展现了如何建立IntentService的子类,如何建立onHandleIntent()回调,如何在AndroidManifest.xml声明IntentService。

建立IntentService

定义一个IntentService的子类,覆盖onHandleIntent()方法:

代码以下:

public class RSSPullService extends IntentService {
    @Override
    protected void onHandleIntent(Intent workIntent) {
        // Gets data from the incoming Intent
        String dataString = workIntent.getDataString();
        ...
        // Do work here, based on the contents of dataString
        ...
    }
}

提示:其余Service正常的回调,像 onStartCommand()在IntentService里会自动调用。在IntentService里,应该避免覆盖这些回调。

在AndroidManifest.xml里定义IntentService

IntentService也是Service),须要在AndroidManifest.xml里注册。

代码以下:

<application
        android:icon="@drawable/icon"
        android:label="@string/app_name">
        ...
        <!--
            Because android:exported is set to "false",
            the service is only available to this app.
        -->
        <service
            android:name=".RSSPullService"
            android:exported="false"/>
        ...
    <application/>

android:name属性指定了IntentService的类名。

note:<service>节点不能包含intent filter。发送工做请求的Activity使用明确的Intent,会指定哪一个IntentService。这也意味着,只有同一个app里的组件,或者另外一个有相同user id的应用才能访问IntentService。

如今你有了基础的IntentService类,能够用Intent对象发送工做请求。

建立发送工做请求传给IntentService

建立一个明确的Intent,添加须要的数据,调用startService()发送给IntentService

代码以下:
/*
 * Creates a new Intent to start the RSSPullService
 * IntentService. Passes a URI in the
 * Intent's "data" field.
 */
mServiceIntent = new Intent(getActivity(), RSSPullService.class);
mServiceIntent.setData(Uri.parse(dataUrl));
//Call startService() 
// Starts the IntentService
getActivity().startService(mServiceIntent);

提示:能够在Activity or Fragment的任意位置发送工做请求。若是你须要先取到用户输入,你能够在点击事件或相似手势的回调方法里发送工做请求。

一旦调用了startService(),IntentService会在onHandleIntent()工做,OK。

Java编程语言建立Windows后台案例:

打开myeclipse,打开敲代码。
  windows服务是一个运行在操做系统后台的可执行程序(打开方式:win+r -> services.msc),咱们平常用到的apache、mysql、tomcat等的启动和关闭都会封装成一个windows服务,随着计算机启动而启动,藏匿在后台,不影响用户的其它工做。 
  今天先分享一个入门级的java建立windows服务的例子。 
   
  1.打包成win服务的功能代码LogService.java 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.text.SimpleDateFormat; 
import java.util.Calendar; 
public class Logservice { 
public static void main(String args[]){ 
Calendar cal = Calendar.getInstance(); 
String s =  "f:\\"+new SimpleDateFormat("yyyyMMddHHmmss").format(cal.getTime())+".txt"; 
System.out.println(s); 
File f = new File(s); 
try { 
FileOutputStream out = new FileOutputStream(f); 
} catch (FileNotFoundException e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 





运行后在f:路径下建立一个日期记事本。 
   2.下载JavaService (http://javaservice.objectweb.org/)下载后解压便可。 
   3.执行建立win服务的命令。在cmd运行窗口,cd到JavaService的目录,输入JavaService.exe -install myService "%JAVA_HO 
ME%"\jre\bin\client\jvm.dll  -Djava.class.path="JAVA_HOME"\lib\tools.jar;F:\myec 
lipse3\javaservice\bin -start Logservice 
(其中,myService为建立的服务名称,%JAVA_HO 
ME%"\jre\bin\client\jvm.dll为jdk中jre的jvm虚拟机,F:\myec 
lipse3\javaservice\bin为我LogService.class的存在路径,请你们根据本身的类文件进行修改。 
需注意问题:JavaService 不支持C:Program Files中间的空格,因此找不到JVM;固尽可能使用"JAVA_HOME",而不要直接用jdk的路径;使用%JAVA_HOME%时又必须在其上加双引号才行,即"%JAVA_HOME%") 

能够执行服务啦,OK
adiOS

相关文章
相关标签/搜索