Android Service
Android Service 类似于Windows 的 Windows Service,由于Windows 服务的作用大家都很熟悉了,这里就不介绍了。今天写了一个简单的例子,介绍Android Service 的使用方式。Android 界面有两个按钮,一个是启动服务,一个是停止服务。
ServiceActivity
package com.example.androidexample; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class ServiceActivity extends Activity { private Button btnStartService; private Button btnStopService; private Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); super.setContentView(R.layout.activity_service); intent = new Intent(); intent.setAction("My_Action"); btnStartService = (Button)super.findViewById(R.id.btnStartService); btnStopService = (Button)super.findViewById(R.id.btnStopService); btnStartService.setOnClickListener(startServiceListener); btnStopService.setOnClickListener(stopServiceListener); } OnClickListener startServiceListener = new OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub startService(intent); } }; OnClickListener stopServiceListener = new OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub stopService(intent); } }; }
FirstService
package com.example.business; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.widget.Toast; import com.example.androidexample.*; public class FirstService extends Service { @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); System.out.println("Service is created."); //Toast.makeText(new ServiceActivity(), "Service is created", Toast.LENGTH_LONG).show(); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); System.out.println("Service is destoryed."); } @Override public int onStartCommand(Intent intent, int flags, int startId) { System.out.println("Service is started."); // TODO Auto-generated method stub return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } }
布局文件 activity_service.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/btnStartService" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/StartService"/> <Button android:id="@+id/btnStopService" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/StopService"/> </LinearLayout>
运行效果