初识 Service(一)

本文详细介绍了Android中服务组件的概念,包括本地服务和远程服务的区别及用法,并通过代码实例展示了如何在Activity中启动、停止这些服务。此外,还附上了用于演示的XML布局文件。

  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>


工程文件可下载: http://download.youkuaiyun.com/detail/gdp2852/3783674
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值