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)来获得通知管理器。来自通知管理器的消息将显示在状态栏中。

更多相关文章

  1. Android方法过多MutiDex使用说明
  2. 修改 android 手机 hosts 文件的方法
  3. android 中 LocalSocket的基本使用方法
  4. android 取消标题 程序意外停解决方法
  5. NDK C++线程中如何调用JAVA API
  6. Android删除Alarm的方法
  7. Android小项目之欢迎滑动页面(最简洁方法)
  8. Android五种隐藏状态栏和标题栏的方法

随机推荐

  1. openGL在surfaceview中实例
  2. Android(安卓)Gitlab CI/CD脚本
  3. Android(安卓)AlertDialog和ProgressDial
  4. 20-b Local Service
  5. Android(安卓)圆角&圆形图片
  6. 【Android(安卓)Audio】Audio: summery o
  7. Android(安卓)菜单 使用XML
  8. 手机客户端版csdn搜索
  9. Android(安卓)check if app debug or rel
  10. Android(安卓)开发笔记第二季 DialogFrag