Service实例

下面通过一个实例演示如何创建、启动、停止及绑定一个Service,具体步骤:

1、创建一个工程,在main.xml中声明四个Button,分别用来启动Service、停止Service、绑定Service和接触绑定Service

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
	<LinearLayout 
		android:orientation="horizontal"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content">
		<Button android:id="@+id/startButton"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content"
			android:layout_weight="1"
			android:text="启动"/>
		<Button android:id="@+id/stopButton"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content"
			android:layout_weight="1"
			android:text="停止"/>
	</LinearLayout>
	
	<LinearLayout 
		android:orientation="horizontal"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content">
		<Button android:id="@+id/bindButton"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content"
			android:layout_weight="1"
			android:text="绑定"/>
		<Button android:id="@+id/unbindButton"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content"
			android:layout_weight="1"
			android:text="解除绑定"/>
	</LinearLayout>
	
</LinearLayout>

 

2、创建一个MyService,继承自Service,覆盖其生命周期中的方法(onCreate、onStart、onDestroy),并在各个方法中显示信息

public class MyService extends Service{

	/* (non-Javadoc)
	 * @see android.app.Service#onBind(android.content.Intent)
	 */
	@Override
	public IBinder onBind(Intent intent) {
		Log.i("Service", "onBind...");
		Toast.makeText(MyService.this, "OnBind...", Toast.LENGTH_LONG).show() ;
		return null;
	}

	@Override
	public void onCreate() {
		Log.i("Service", "onCreate...");
		Toast.makeText(MyService.this, "onCreate...", Toast.LENGTH_LONG).show() ;
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		Log.i("Service", "onDestroy...");
		Toast.makeText(MyService.this, "onDestroy...", Toast.LENGTH_LONG).show() ;
		super.onDestroy();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		Log.i("Service", "onStart...");
		Toast.makeText(MyService.this, "onStart...", Toast.LENGTH_LONG).show() ;
		super.onStart(intent, startId);
	}
}

 

3、在AndroidManifest.xml配置文件中声明activity和service

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.newcosoft.service"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
		<service android:name="MyService">
			<intent-filter>
				<action android:name="com.newcosoft.service.action.MY_SERVICE"></action>
			</intent-filter>
		</service>
    </application>
</manifest>

 

4、接下来在MainActivity分别创建四个OnClickListener监听和ServiceConnection

public class MainActivity extends Activity {
	private Button startButton,stopButton,bindButton,unbindButton;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        startButton = (Button) this.findViewById(R.id.startButton);
        stopButton = (Button) this.findViewById(R.id.stopButton);
        bindButton = (Button) this.findViewById(R.id.bindButton);
        unbindButton = (Button) this.findViewById(R.id.unbindButton);
        
        startButton.setOnClickListener(startOnClickListener);
        stopButton.setOnClickListener(stopOnClickListener);
        bindButton.setOnClickListener(bindOnClickListener);
        unbindButton.setOnClickListener(unbindOnClickListener);
        
    }
    //启动Service监听器
    private OnClickListener startOnClickListener = new OnClickListener(){

		@Override
		public void onClick(View v) {
			Intent intent = new Intent();
			intent.setAction("com.newcosoft.service.action.MY_SERVICE");
			startService(intent);
		}
    	
    };
    
    //停止Service监听器
    private OnClickListener stopOnClickListener = new OnClickListener(){

		@Override
		public void onClick(View v) {
			Intent intent = new Intent();
			intent.setAction("com.newcosoft.service.action.MY_SERVICE");
			stopService(intent);
		}
    	
    };
    
    //创建连接对象
    private ServiceConnection conn = new ServiceConnection(){

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.i("MainActivity", "onServiceConnected");
			Toast.makeText(MainActivity.this, "连接成功!", Toast.LENGTH_LONG);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.i("MainActivity", "onServiceDisconnected");
			Toast.makeText(MainActivity.this, "断开连接成功!", Toast.LENGTH_LONG);
		}
    	
    };
    
    //绑定Service监听器
    private OnClickListener bindOnClickListener = new OnClickListener(){

		@Override
		public void onClick(View v) {
			Intent intent = new Intent();
			intent.setAction("com.newcosoft.service.action.MY_SERVICE");
			//指定自动创建
			bindService(intent, conn, BIND_AUTO_CREATE);
		}
    	
    };
    
    //接触绑定Service监听器
    private OnClickListener unbindOnClickListener = new OnClickListener(){

		@Override
		public void onClick(View v) {
			Intent intent = new Intent();
			intent.setAction("com.newcosoft.service.action.MY_SERVICE");
			unbindService(conn);
		}
    	
    };
    
    
}

 

运行结果如下:



 

<think>首先,用户的问题是关于在C#中创建和使用Service实例的。用户提到了Windows Service,所以我需要基于提供的引用内容来构建回答。 从引用中: - 引用[1]展示了如何创建一个Windows Service类,继承自ServiceBase,并重写OnStart和OnStop方法。 - 引用[2]讨论了如何使用ServiceController类来控制服务,如启动、停止、暂停等。 - 引用[3]提到了一个web service的使用实例,但这不是Windows Service;它是web service。 - 引用[4]解释了如何安装和卸载Windows Service使用installutil工具。 用户的问题焦点是“Service实例”,但从上下文看,用户可能指的是Windows Service,因为引用[1]、[2]和[4]都涉及Windows Service。引用[3]是关于web service的,所以我需要区分清楚。 我的回答应该: - 使用中文回答。 - 结构清晰,逐步解决问题。 - 确保回答真实可靠。 - 在行内数学表达式使用$...$格式(但在这个上下文中,可能不涉及数学表达式)。 - 独立公式使用$$...$$格式(同样,可能不适用)。 - LaTeX语法正确(但这里主要是代码,不是数学)。 - 生成相关问题。 - 在引用的段落末尾添加引用标识,如[^1]。 步骤: 1. **介绍Windows Service**:解释什么是Windows Service及其用途。 2. **创建Windows Service**: - 创建一个继承自ServiceBase的类。 - 重写OnStart、OnStop等方法。 - 添加事件日志或其他功能。 - 基于引用[1]的代码示例。 3. **安装和卸载Service**: - 使用installutil工具,如引用[4]所述。 4. **使用ServiceController**: - 如何启动、停止、暂停服务,如引用[2]所示。 5. **区分其他Service类型**:简要提到web service(如引用[3]),但澄清用户可能指的是Windows Service。 6. **生成相关问题**:在回答末尾添加相关问题。 回答结构: - 开头解释主题。 - 逐步讲解创建和使用。 - 提供代码示例(使用代码块)。 - 引用相关部分。 - 最后生成相关问题。 确保代码正确: - 从引用[1]中提取代码,并确保它完整。 - 引用[2]的代码片段展示如何控制服务。 - 引用[4]的安装步骤。 最终输出: - 以用户可见层开始。 - 结束于相关问题。</think>### 在C#中创建和使用Service实例(Windows Service) 在C#中,Service实例通常指Windows Service,它是一种后台运行的应用程序,用于执行长时间任务(如定时作业或系统监控)。下面我将分步骤解释如何创建和使用Windows Service实例,确保内容清晰可靠。注意:本回答主要基于Windows Service,但也会简要区分其他Service类型(如Web Service)。 #### 1. **创建Windows Service类** 首先,创建一个继承自`ServiceBase`的类,并重写关键方法(如`OnStart`和`OnStop`)。以下是完整示例代码,基于引用[1]: ```csharp using System; using System.Diagnostics; using System.ServiceProcess; namespace MyWindowsService { public class MyService : ServiceBase { // 可选:添加事件日志用于调试 private EventLog eventLog; public MyService() { // 初始化服务名称和日志 ServiceName = "MyFirstService"; eventLog = new EventLog(); if (!EventLog.SourceExists(ServiceName)) { EventLog.CreateEventSource(ServiceName, "Application"); } eventLog.Source = ServiceName; } protected override void OnStart(string[] args) { // 服务启动时执行的代码 eventLog.WriteEntry("Service started successfully", EventLogEntryType.Information); // 添加您的业务逻辑,例如定时任务 } protected override void OnStop() { // 服务停止时执行的代码 eventLog.WriteEntry("Service stopped", EventLogEntryType.Information); // 清理资源 } // 可选:重写其他方法如OnPause、OnContinue protected override void OnPause() { eventLog.WriteEntry("Service paused"); } protected override void OnContinue() { eventLog.WriteEntry("Service resumed"); } } } ``` - **关键点**: - `OnStart`方法在服务启动时触发,用于初始化任务。 - `OnStop`方法在服务停止时执行清理。 - 使用`EventLog`记录日志,便于调试[^1]。 - 服务名称(`ServiceName`)用于后续安装和控制。 #### 2. **安装和卸载Windows Service** 创建服务后,需使用`installutil`工具安装到系统。步骤如下: - 编译项目生成.exe文件(例如`MyService.exe`)。 - 以管理员身份打开命令提示符,运行安装命令: ```bash installutil MyService.exe ``` - 卸载服务时,添加`/u`参数: ```bash installutil /u MyService.exe ``` - **注意**:`installutil.exe`通常位于.NET Framework目录(如`C:\Windows\Microsoft.NET\Framework\v4.0.30319`),如果环境变量未设置,需指定完整路径[^4]。 #### 3. **使用ServiceController控制服务实例** 安装后,可通过`ServiceController`类在代码中启动、停止或检查服务状态。示例基于引用[2]: ```csharp using System.ServiceProcess; public class ServiceManager { public static void Main() { string serviceName = "MyFirstService"; // 与服务名称一致 ServiceController sc = new ServiceController(serviceName); // 启动服务 if (sc.Status == ServiceControllerStatus.Stopped) { sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running); Console.WriteLine("Service started."); } // 停止服务 if (sc.CanStop && sc.Status == ServiceControllerStatus.Running) { sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped); Console.WriteLine("Service stopped."); } // 暂停或继续服务 if (sc.CanPauseAndContinue) { if (sc.Status == ServiceControllerStatus.Running) { sc.Pause(); Console.WriteLine("Service paused."); } else if (sc.Status == ServiceControllerStatus.Paused) { sc.Continue(); Console.WriteLine("Service resumed."); } } // 检查服务状态 Console.WriteLine($"Current status: {sc.Status}"); } } ``` - **关键点**: - `ServiceController`提供对服务的运行时控制。 - 使用`CanStop`和`CanPauseAndContinue`检查服务能力。 - `WaitForStatus`确保操作完成[^2]。 #### 4. **区分其他Service类型** - **Windows Service vs. Web Service**: - Windows Service是系统级后台服务(如上所述)。 - Web Service是网络API,使用不同技术(如WCF或ASP.NET)。创建Web Service时,通常定义接口并通过HTTP调用,例如引用[3]中的简单示例: ```csharp // Web Service客户端调用示例 ServiceReference1.Servics1SoapClient client = new ServiceReference1.Servics1SoapClient(); string result = client.HelloWorld(); Console.WriteLine(result); ``` 但这不是Windows Service,需单独处理[^3]。 #### 5. **最佳实践和注意事项** - **调试技巧**:安装服务后,在Visual Studio中使用“附加到进程”调试(选择`svchost.exe`进程)。 - **可靠性**:服务中避免长时间阻塞操作;使用线程或异步任务。 - **安全性**:以管理员权限运行安装和控制代码。 - **常见错误**:如果服务无法启动,检查事件日志(`Event Viewer`)中的错误消息。 通过以上步骤,您可以成功创建和使用Windows Service实例。如果您需要Web Service的详细指南,请说明,我会补充。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值