博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
android基础---->IntentService的使用
阅读量:4972 次
发布时间:2019-06-12

本文共 8186 字,大约阅读时间需要 27 分钟。

  这一篇博客,我们开始前台服务与IntentServie源码分析的学习,关于service的生命周期及其简单使用,请参见我的博客:()

 

目录导航:

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  

 

服务的简单说明

一、 前台服务与IntentService:

  • 前台服务可以一直保持运行状态,而不会由于系统内存不足的原因导致被回收

 

service服务测试的准备代码

我们通过一个具体的案例来说明start与bind方式的service服务的生命周期的介绍。项目结果如下:

 

一、 在MainActivity.java中做一些初始化工作,如下代码:

private final static String TAG = "MyIntentService";private MyIntentService.MyBinder binder;private ServiceConnection connection = new ServiceConnection() {    @Override    public void onServiceConnected(ComponentName name, IBinder service) {        binder = (MyIntentService.MyBinder) service;        binder.sayHello(name.getClassName());    }    @Override    public void onServiceDisconnected(ComponentName name) {        Log.i(TAG, "service disconnect: " + name.getClassName());    }};@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);}

 

二、 创建一个简单的IntentService服务类:MyIntentService

package com.example.linux.intentservicetest;import android.app.IntentService;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.util.Log;public class MyIntentService extends IntentService {    private final static String TAG = "MyIntentService";    private MyBinder myBinder = new MyBinder();    class MyBinder extends Binder {        public void sayHello(String name) {            Log.i(TAG, "say hello method: " + name);        }        public void sayWorld(String name) {            Log.i(TAG, "say world method: " + name);        }    }    @Override    public IBinder onBind(Intent intent) {        return myBinder;    }    public MyIntentService() {        super("MyIntentService");        Log.i(TAG, "myintent service constructor.");    }    @Override    public void onCreate() {        Log.i(TAG, "on create.");        super.onCreate();    }    @Override    protected void onHandleIntent(Intent intent) {        Log.i(TAG, "handle intent: " + intent.getStringExtra("username") + ", thread: " + Thread.currentThread());    }    @Override    public void onDestroy() {        super.onDestroy();        Log.i(TAG, "on destroy.");    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        Log.i(TAG, "on start command.");        return super.onStartCommand(intent, flags, startId);    }    @Override    public boolean onUnbind(Intent intent) {        //默认返回false        String username = intent.getStringExtra("username");        Log.i(TAG, "on unbind: " + super.onUnbind(intent) + ", username: " + username);        return true;    }    @Override    public void onRebind(Intent intent) {        Log.i(TAG, "on rebind");        super.onRebind(intent);    }}

 

 三、 创建一个简单的前台服务类:FrontService

package com.example.linux.intentservicetest;import android.app.Notification;import android.app.PendingIntent;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;public class FrontService extends Service {    private final static String TAG = "MyIntentService";    public FrontService() {        Log.i(TAG, "front service constructor");    }    @Override    public IBinder onBind(Intent intent) {        return null;    }    @Override    public void onCreate() {        super.onCreate();        Notification.Builder builder = new Notification.Builder(this);        Intent intent = new Intent(this, MainActivity.class);        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,                PendingIntent.FLAG_CANCEL_CURRENT);        builder.setSmallIcon(R.mipmap.ic_launcher).setTicker("ticker");        builder.setWhen(System.currentTimeMillis()).setAutoCancel(true);        builder.setContentTitle("content title").setContentText("content text");        builder.setContentIntent(pendingIntent);        Notification notify = builder.getNotification();        notify.defaults = Notification.DEFAULT_ALL;        startForeground(10, notify);    }}

 

四、 在AndroidManifest.xml中注册服务与活动:

 

Intent服务的使用

一、 在MainActivity中创建方法,启动停止服务:

// 开启服务public void startService(View view) {    Intent intent = new Intent();    intent.putExtra("username", "linux");    intent.setClass(MainActivity.this, MyIntentService.class);    startService(intent);}// 停止服务public void stopService(View view) {    Intent intent = new Intent();    intent.setClass(MainActivity.this, MyIntentService.class);    stopService(intent);}

 

二、 在MainActivity中创建方法,绑定解绑服务:

// 绑定服务public void bindService(View view) {    Intent intent = new Intent();    intent.setClass(MainActivity.this, MyIntentService.class);    intent.putExtra("username", "linux");    boolean isBind = bindService(intent, connection, Context.BIND_AUTO_CREATE);    Log.i(TAG, "bind service: " + isBind);}// 解绑服务public void unbindService(View view) {    Intent intent = new Intent();    intent.setClass(MainActivity.this, MyIntentService.class);    unbindService(connection);}

 

三、 运行结果:

  • 点击start:
03-25 08:01:53.460 8389-8389/? I/MyIntentService: myintent service constructor.03-25 08:01:53.460 8389-8389/? I/MyIntentService: on create.03-25 08:01:53.475 8389-8389/? I/MyIntentService: on start command.03-25 08:01:53.477 8389-8727/? I/MyIntentService: handle intent: linux, thread: Thread[IntentService[MyIntentService],5,main]03-25 08:01:53.478 8389-8389/? I/MyIntentService: on destroy.
  • 点击stop:无输出
  • 点击bind:
03-25 08:02:25.421 8389-8389/? I/MyIntentService: bind service: true03-25 08:02:25.422 8389-8389/? I/MyIntentService: myintent service constructor.03-25 08:02:25.422 8389-8389/? I/MyIntentService: on create.03-25 08:02:25.432 8389-8389/? I/MyIntentService: say hello method: com.example.linux.intentservicetest.MyIntentService
  • 点击unbind:
03-25 08:02:28.486 8389-8389/? I/MyIntentService: on unbind: false, username: linux03-25 08:02:28.490 8389-8389/? I/MyIntentService: on destroy.

 

前台服务的使用

一、 在MainActivity中创建方法,启动前台服务:

// 前台服务的使用public void frontService(View view) {    Intent intent = new Intent();    intent.setClass(MainActivity.this, FrontService.class);    startService(intent);}

 

二、 运行结果: 在手机的通知栏中

 

IntentService的原理分析

一、 intentService是继承Service的抽象方法:

public abstract class IntentService extends Service

 

二、 intentService包含的一些字段引用如下:

private volatile Looper mServiceLooper;private volatile ServiceHandler mServiceHandler;private String mName;private boolean mRedelivery;private final class ServiceHandler extends Handler {    public ServiceHandler(Looper looper) {        super(looper);    }    @Override    public void handleMessage(Message msg) {        onHandleIntent((Intent)msg.obj);        stopSelf(msg.arg1);    }}

 

二、 和service一样在启动的时候,首先是执行构造方法,接着是onCreate方法,然后是onStartCommand方法,在onStartCommand中执行了onStart方法(执行流程在讲过):

  • onCreate方法,开启了一个线程,并且得到Looper与初始化了一个Handler
@Overridepublic void onCreate() {    // TODO: It would be nice to have an option to hold a partial wakelock    // during processing, and to have a static startService(Context, Intent)    // method that would launch the service & hand off a wakelock.    super.onCreate();    HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");    thread.start();    mServiceLooper = thread.getLooper();    mServiceHandler = new ServiceHandler(mServiceLooper);}
  • onStart方法,用上述的Handler发送信息
@Overridepublic void onStart(Intent intent, int startId) {    Message msg = mServiceHandler.obtainMessage();    msg.arg1 = startId;    msg.obj = intent;    mServiceHandler.sendMessage(msg);}
  • onStartCommand方法,调用onStart方法,发送信息
@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {    onStart(intent, startId);    return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;}
  • 最后上述的Handler得到信息,调用handleMessage方法,其中有stopSelf(msg.arg1)方法,停止了服务:

 

三、 这里附上service类的两个方法,源代码是android6.0的

  • 在Service中的onStart方法已经被废弃了:
/** * @deprecated Implement {
@link #onStartCommand(Intent, int, int)} instead.*/@Deprecatedpublic void onStart(Intent intent, int startId) {}
  • 在onStartCommand的方法中
public int onStartCommand(Intent intent, int flags, int startId) {    onStart(intent, startId);    return mStartCompatibility ? START_STICKY_COMPATIBILITY : START_STICKY;}

 

友情链接

  • 关于服务的生命周期与简单使用:                ()
  • :                                   访问密码 a840

 

转载于:https://www.cnblogs.com/huhx/p/intentService.html

你可能感兴趣的文章
别过来,过来我就撕票了!
查看>>
并发模型—共享内存模型(线程与锁)示例篇
查看>>
正则表达式---------------嵌套的分组
查看>>
转Keil 中使用 STM32F4xx 硬件浮点单元
查看>>
分区命令
查看>>
FreeBSD releaning(6)-chmod
查看>>
C语言各数据类型大小和取值范围
查看>>
InsetDrawable
查看>>
oracle的sql执行计划
查看>>
python-函数(装饰器)
查看>>
面向对象
查看>>
Oracle对没有主键的表分页
查看>>
Scilab 的画图函数(2)
查看>>
apache 和 Tomcat 安全性配置
查看>>
[Luogu] 引水入城
查看>>
86. Partition List
查看>>
154. Find Minimum in Rotated Sorted Array II
查看>>
3-bash内部命令变量
查看>>
设计模式 适配器模式(Adapter Pattern)
查看>>
zipfile
查看>>