- package eoe.Demo;
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- public class Activity01 extends Activity {
- private static final String TAG = "Activity01";
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Log.d(TAG, "starting service");
- Button bindBtn = (Button) findViewById(R.id.bindBtn);
- bindBtn.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- startService(new Intent(Activity01.this,
- BackgroundService.class));
- }
- });
- Button unbindBtn = (Button) findViewById(R.id.unbindBtn);
- unbindBtn.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- stopService(new Intent(Activity01.this, BackgroundService.class));
- }
- });
- }
- }
Java代码:
- <?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"
- >
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello"
- />
- <Button android:id="@+id/bindBtn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Bind"/>
- <Button android:id="@+id/unbindBtn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="UnBind"/>
- </LinearLayout>
我们需要创建一个图标 并将其放在项目的drawable文件夹内,我用的项目自带的那个。需要为通知管理器NotificationManager提供一个应用程序级唯一ID(整数)。要创建唯一ID,可以向字符串资源文件 /res/values/strings.xml 添加一个项ID。当调用notify()方法时,会将唯一ID 传递给通知管理器。
Java代码:
- <item type=”id” name=”app_notification_id”/>
Java代码:
- <service android:name=”BackgroundService”/>
标记,将其作为<application>的子标签。
BackgroundServie是承载服务的应用程序组件使用服务的一个典型例子。换言之,运行服务的应用程序也是服务的唯一使用者。因为该服务不支持其进程外的客户端,所以它是本地服务。由于本地服务不是远程服务,所以它在bind()方法中返回null。因此,绑定此服务的唯一 方法是调用Context.startService()。本地服务的重要方法包括 onCreate()、onStart()、stop()*和onDestroy()。
在BackgroundService的 onCreate()方法中,我们创建了一个线程来完成服务的主要工作。我们需要应用程序的主线程来处理用户界面,所以将服务的工作委派给一个辅助线程。另请注意,我们在onCreate()而不是onStart()中创建和启动线程。这样做是因为, onCreate()只会被调用一次,我们也希望在服务生命周期内只创建一次该线程。onStart()方法可以调用多次,所以它不符合此处的要求。我们在线程的run()方法实现中没有做任何事情,可以在这里执行HTTP调用、查询数据库等。
BackgroundService还使用NotificationManager类,以在服务启动和停止时向用户发送通知。这是本地服务将信息传递回用户的一种方式。要向用户发送通知,需要调用 getSystemService(NOTIFICATION_SERVICE)来获得通知管理器。来自通知管理器的消息将显示在状态栏中。

被折叠的 条评论
为什么被折叠?



