service 是后台运行的组件,没有用户界面。 Android支持两种类型的service:Local Service 本地服务和 Remote 远程服务。本地服务无法供设备上运行的其他APP访问,仅运动承载该服务的应用程序。
远程服务可从承载服务的应用程序访问,还可从其他应用程序访问。
简单地说,就是本地服务就是你自个的应用程序可以用。远程服务可供你的和其它的APP使用,远程服务使用AIDL向客户端定义本身。
不多说,上代码:
Activity 定义了两个按钮,一个是startService, 一个是stop service
public class Demo_ServiceActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.bindBtn).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startService(new Intent(Demo_ServiceActivity.this,BackgroundService.class));
}
});
findViewById(R.id.unbindBtn).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
stopService(new Intent(Demo_ServiceActivity.this, BackgroundService.class));
}
});
}
}
Service 也简单,代码如下:
public class BackgroundService extends Service {
private NotificationManager notificationMrg;
public void onCreate() {
super.onCreate();
notificationMrg = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
displayNotificationMessage("starting Background Service");
doInBackground();
}
private void doInBackground() {
new Thread(new Runnable() {
public void run() {
//TODO do what you wanna to do
}
}).start();
}
@Override
public void onDestroy() {
displayNotificationMessage("stopping Background Service");
super.onDestroy();
}
public IBinder onBind(Intent intent) {
return null;
}
private void displayNotificationMessage(String message) {
Notification notification = new Notification(R.drawable.sina, message,
System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, Demo_ServiceActivity.class), 0);
notification.setLatestEventInfo(this, "Background Service", message,
contentIntent);
notificationMrg.notify(R.id.app_notification_id, notification);
}
}
还有一个main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:id="@+id/bindBtn" android:text="Bind"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<Button android:id="@+id/unbindBtn" android:text="UnBind"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</LinearLayout>