android教程之service使用方法示例详解
发布时间:2023-05-08 03:48:21
标签:android,service
Service的生命周期 (适用于2.1及以上)
1. 被startService的
无论是否有任何活动绑定到该Service,都在后台运行。onCreate(若需要) -> onStart(int id, Bundle args). 多次startService,则onStart调用多次,但不会创建多个Service实例,只需要一次stop。该Service一直后台运行,直到stopService或者自己的stopSelf()或者资源不足由平台结束。
2. 被bindService的
调用bindService绑定,连接建立服务一直运行。未被startService只是BindService,则onCreate()执行,onStart(int,Bundle)不被调用;这种情况下绑定被解除,平台就可以清除该Service(连接销毁后,会导致解除,解除后就会销毁)。
3. 被启动又被绑定
类似startService的生命周期,onCreate onStart都会调用。
4. 停止服务时
stopService时显式onDestroy()。或不再有绑定(没有启动时)时隐式调用。有bind情况下stopService()不起作用。
以下是一个简单的实现例子,某些部分需要配合logcat观察。
AcMain.java
package jtapp.myservicesamples;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class AcMain extends Activity implements OnClickListener {
private static final String TAG = "AcMain";
private Button btnStart;
private Button btnStop;
private Button btnBind;
private Button btnExit;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findView();
}
private void findView() {
btnStart = (Button) findViewById(R.id.Start);
btnStop = (Button) findViewById(R.id.Stop);
btnBind = (Button) findViewById(R.id.Bind);
btnExit = (Button) findViewById(R.id.Exit);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
btnBind.setOnClickListener(this);
btnExit.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = new Intent("jtapp.myservicesamples.myservice");
switch(v.getId()) {
case R.id.Start:
startService(intent);
Toast.makeText(this,
"myservice running " + MyService.msec/1000.0 + "s.",
Toast.LENGTH_LONG).show();
break;
case R.id.Stop:
stopService(intent);
Toast.makeText(this,
"myservice running " + MyService.msec/1000.0 + "s.",
Toast.LENGTH_LONG).show();
break;
case R.id.Bind:
bindService(intent, sc, Context.BIND_AUTO_CREATE);
break;
case R.id.Exit:
this.finish();
break;
}
}
private MyService serviceBinder;
private ServiceConnection sc = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d(TAG, "in onServiceDisconnected");
serviceBinder = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d(TAG, "in onServiceConnected");
serviceBinder = ((MyService.MyBinder)service).getService();
}
};
@Override
protected void onDestroy() {
//this.unbindService(sc);
//this.stopService(
// new Intent("jtapp.myservicesamples.myservice"));
super.onDestroy();
}
}
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">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello" />
<Button android:text="Start MyService" android:id="@+id/Start"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<Button android:text="Stop MyService" android:id="@+id/Stop"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<Button android:text="Bind MyService" android:id="@+id/Bind"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<Button android:text="Exit AcMain" android:id="@+id/Exit"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</LinearLayout>
MyService.java
package jtapp.myservicesamples;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
private static final String TAG = "MyService";
public static long msec = 0;
private boolean bThreadRunning = true;
private final IBinder binder = new MyBinder();
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
@Override
public void onCreate() {
new Thread(new Runnable(){
@Override
public void run() {
while (bThreadRunning) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
Log.i(TAG, "myservice running " + (msec+=100) + "ms.");
}
}
}).start();
}
@Override
public void onDestroy() {
bThreadRunning = false;
super.onDestroy(); // 可以不用
}
}
AnndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="jtapp.myservicesamples" android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:debuggable="true">
<activity android:name=".AcMain" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="MyService">
<intent-filter>
<action android:name="jtapp.myservicesamples.myservice"></action>
</intent-filter>
</service>
</application>
</manifest>


猜你喜欢
- 先看一组加载效果图,有点粉粉的加载圈: 自定义这样的圆形加载圈还是比较简单的,主要是用到Canvans的绘制文本,绘制圆和绘制圆弧的api:
- 要求:如下图,使用线程操作 1、实时显示当前时间 2、输入加数和被加数,自动出现结果 分析:两个问题解决的方式一致,使用子线程进
- 什么是代理模式?代理模式:在调用处不直接调用目标类进行操作,而是调用代理类,然后通过代理类来调用目标类进行操作。在代理类调用目标类的前后可以
- 1.servlet:定义:接口2.配置servlet:public class HelloServlet extends HttpServl
- 准备学习java2游戏编程。(其实这是一本书啦)然后作为基础的基础的基础,必须学习如何让键盘与界面进行交互。下面就是对一个基础得不能再基础的
- PictureBox 控件可以显示来自位图、图标或者元文件,以及来自增强的元文件、JPEG 或 GIF 文件的图形。如果控件不足以显示整幅图
- 1、加载节点SpringBoot启动时,会执行这个方法:SpringApplication#run,这个方法中会调prepareContex
- 本文实例讲述了C#快速排序算法。分享给大家供大家参考。具体实现方法如下:public static int[] QuickSort(int[
- 关于springmvc上传图片的方法小编给大家整理了两种方法,具体内容如下所示:第一种:(放在该项目下的物理地址对应的位置)a. 路径写法:
- ConstantConstant 和 ConstantPool 是用于表示常量的一种机制。Constant 接口定义了常量的基本属性和方法,
- 本文实例讲述了C#图像处理之边缘检测(Sobel)的方法。分享给大家供大家参考。具体如下://定义sobel算子函数private stat
- 一、使用方式可以采用Transactional,配置propagation即可。打开org.springframework.transact
- 说起空间动态、微博的点赞效果,网上也是很泛滥,各种实现与效果一大堆。而详细实现的部分,讲述的也是参差不齐,另一方面估计也有很多大侠也不屑一顾
- 在Java里面,可以用复制语句”A=B”给基本类型的数
- 我们开发一个Spring Boot项目,肯定要导入许多的静态资源,比如css,js等文件如果我们是一个web应用,我们的main下会有一个w
- 前言实现轨迹回放,GMap.NET有对应的类GMapRoute。这个类函数很少,功能有限,只能实现简单的轨迹回放。要实现更复杂的轨迹回放,就
- 一、插入排序算法实现java版本public static int[] insert_sort(int[] a){for (int i =
- 在传统的Java编程中,被广为人知的一个知识点是:java Interface接口中不能定义private私有方法。只允许我们定义publi
- 删除本地仓库未下载完成的缓存文件(删除像图片显示这样以.lastUpdated结尾的文件)执行mvn -v确保maven命令可以正常执行执行
- 案例:图书管理(SpringBoot+Thymeleaf+SpringData-JPA)添加图书:图书基本信息及封面图片的上传及入库图书详细