Android 服务(本地服务示例)(二)

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));
}
});
}
}


<?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 传递给通知管理器。


<item type=”id” name=”app_notification_id”/>
<service android:name=”BackgroundService”/>

BackgroundServie是承载服务的应用程序组件使用服务的一个典型例子。换言之,运行服务的应用程序也是服务的唯一使用者。因为该服务不支持其进程外的客户端,所以它是本地服务。由于本地服务不是远程服务,所以它在bind()方法中返回null。因此,绑定此服务的唯一 方法是调用Context.startService()。本地服务的重要方法包括 onCreate()、onStart()、stop()*和onDestroy()。

在BackgroundService的 onCreate()方法中,我们创建了一个线程来完成服务的主要工作。我们需要应用程序的主线程来处理用户界面,所以将服务的工作委派给一个辅助线程。另请注意,我们在onCreate()而不是onStart()中创建和启动线程。这样做是因为, onCreate()只会被调用一次,我们也希望在服务生命周期内只创建一次该线程。onStart()方法可以调用多次,所以它不符合此处的要求。我们在线程的run()方法实现中没有做任何事情,可以在这里执行HTTP调用、查询数据库等。

BackgroundService还使用NotificationManager类,以在服务启动和停止时向用户发送通知。这是本地服务将信息传递回用户的一种方式。要向用户发送通知,需要调用 getSystemService(NOTIFICATION_SERVICE)来获得通知管理器。来自通知管理器的消息将显示在状态栏中。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值