Create Started Service

先说 一下Service .


1.什么是Service?按照官方的API,分为一下两点:

、Service不是一个单独的进程。服务对象本身并不意味着它运行在自己的过程,除非另有规定,它运行在同一进程中是应用程序的一部分.

、Service不是一个线程。也就是说它不用依赖主线程进行工作(避免应用程序没有响应错误)。

2.因此,服务本身其实很简单,提供两个主要特点:
   ①、它是应用程序在系统后台处理某些工作的场所(即使用户不直接与应用程序交互)。这对应的需要调用的方法是Context.startService(),
这样的话它就处于started状态,一旦启动,就会在后台无限期的进行,即使启动它的组建已经被销毁,也会一直运行这样的话就会要求系统调度
Service进行工作处理,去运行服务或者是进行明确 的进行停止它运行。
   ②、它是一个某个应用程序向另一个应用程序公开进行传递数据的一个场所,这个调用的方法是Context.binService()这个方法,允许一个长
期存在的连接的服务来与之交互。允许组件与服务交互,发送请求,获取结果,甚至进程间通信跨进程完成这些操作。仅当其他应用程序组件与之
绑定时,绑定服务才运行。

3.Service类中重要方法:
onStartCommand()--当组件如(Activity)调用startService()方法后就会在后台无限期运行,处于started状态,开发人员需要在利用完Service
处理完事件后进行调用stopSelf()或者是stopService(),停止进行后台运行如果仅仅想提供绑定,不必实现这个方法。
onBind()--当其他组件调用bindService()方法想与服务绑定时调用该方法,在这个方法实现中开发者必须返回IBinder提供客户端用来与服务
通信接口,该方法必须实现,但是如果不想允许绑定,则返回null.
onCreate()--在第一次创建时调用,在系统调用onStaerCommand()或onBind()方法前。
onDestroy()--销毁,这是服务收到的最后调用。

4.需要注意的是在使用服务的时候需要在AndroidManifest.xml中进行注册。

5.主要是采用两种方式进行使用Service.
   ①、一种是集成IntentService,这种方式适用于启动的服务不必同时处理多个请求(单线程)是这样的话就适用仅仅继承IntentSerivce类就行了,里面
仅仅依靠一个重写一个onHandleIntent()方法就行。
   ②、另一种就是继承Service类了,这个就要麻烦多了,但是这个可以创建多个线程,进行多个线程通并发处理。


写的程序主要是实现两个功能,来描述这两中方式的使用,就是使线程停一段时间再进行运行下边的程序。

一、采用继承IntentService的方式


package com.example.hejingzhou.servicedemo;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

/**
 * Created by Hejingzhou on 2016/4/28.
 */
public class IntentServiceClass extends IntentService {
    private int WAITTIME = 3000;
    private String TAG = getClass().getCanonicalName();

    public IntentServiceClass() {
        super("IntentServiceClass");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        long endTime = System.currentTimeMillis() + WAITTIME;
        Log.i(TAG, "等待前-当前时间   " + System.currentTimeMillis());
        while (System.currentTimeMillis() < endTime) {
            synchronized (this) {
                try {
                    wait(endTime - System.currentTimeMillis());//让线程等待 WAITTIME 秒钟
                    Log.i(TAG, "等待后-当前时间   " + System.currentTimeMillis());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

二、采用继承Service


package com.example.hejingzhou.servicedemo;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by Hejingzhou on 2016/4/28.
 */
public class ServiceClass extends Service {
    private String TAG = getClass().getCanonicalName();
    private int WAITTIME = 4000;
    private Looper serLooper;
    private ServiceHandler serviceHandler;

    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            long endTime = System.currentTimeMillis() + WAITTIME;
            while (System.currentTimeMillis() < endTime) {
                synchronized (this) {
                    try {
                        wait(endTime - System.currentTimeMillis());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            stopSelf(msg.arg1);
        }
    }

    @Override
    public void onCreate() {
        HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();
        serLooper = thread.getLooper();
        serviceHandler = new ServiceHandler(serLooper);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "服务开始");
        Message message = serviceHandler.obtainMessage();
        message.arg1 = startId;
        serviceHandler.sendMessage(message);
        return START_STICKY;

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "服务销毁");
    }
}

三、MainActivity


package com.example.hejingzhou.servicedemo;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private String TAG = getClass().getCanonicalName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById();
    }

    private void findViewById() {
        Button btnIntent = (Button) findViewById(R.id.buttonIntentService);
        btnIntent.setOnClickListener(this);
        Button btnService = (Button) findViewById(R.id.buttonService);
        btnService.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.buttonIntentService:
                startService(new Intent(getApplicationContext(), IntentServiceClass.class));
                break;
            case R.id.buttonService:
                startService(new Intent(getApplicationContext(), ServiceClass.class));
                break;
        }
    }
}

四、最后千万别忘了进行注册声明:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.hejingzhou.servicedemo">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

<pre name="code" class="java"><service android:name=".IntentServiceClass"></service>
        <service android:name=".ServiceClass"></service>
 
 
    </application>

</manifest>








啧啧啧 ,一点多了,上床睡觉。。。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值