Android多线程编程技术之使用IntentService

运行截图
这里写图片描述

这里写图片描述

可以看到,不仅MyIntentService 和MainActivity所在的线程id不一样,而且onDestory()方法的得到了执行,说明MyIntentService在运行完毕后确实自动停止了。集开启线程和自动停止线程于一身。

MainActivity.java

package lbstest.example.com.lbs.ServiceTest;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import lbstest.example.com.lbs.R;

public class Main3Activity extends AppCompatActivity implements View.OnClickListener {

    private MyService.DownloadBinder downloadBinder;
    //创建一个ServiceConnection匿名类

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadBinder = (MyService.DownloadBinder) service;
            downloadBinder.startDownload();
            downloadBinder.getProgress();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        Button bindService = (Button) findViewById(R.id.bing_service);
        Button unbindService = (Button) findViewById(R.id.unbing_service);
        Button startService = (Button) findViewById(R.id.start_service);
        Button stopService = (Button) findViewById(R.id.stop_service);
        Button start_intent_service = (Button) findViewById(R.id.start_intent_service);
        start_intent_service.setOnClickListener(this);
        startService.setOnClickListener(this);
        stopService.setOnClickListener(this);
        bindService.setOnClickListener(this);
        unbindService.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bing_service:
                Intent bindIntent = new Intent(this, MyService.class);
                bindService(bindIntent, connection, BIND_AUTO_CREATE); //绑定服务
                break;
            case R.id.unbing_service:
                unbindService(connection); //解绑服务
                break;
            case R.id.start_service:
                Intent startIntent = new Intent(this, MyService.class);
                startService(startIntent);//启动服务
                break;
            case R.id.stop_service:
                Intent stopIntent = new Intent(this,MyService.class);
                stopService(stopIntent);//停止服务
                break;
            case R.id.start_intent_service:
                //打印主线程id
                Log.d("MyIntentService","Thread is"+Thread.currentThread().getId());
                Intent intentService = new Intent(this, MyIntentService.class);
                startService(intentService);
                break;
            default:
                break;
        }
    }
}

MyIntentService.java

package lbstest.example.com.lbs.ServiceTest;

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

/**
 * Created by bummer on 2017/7/26.
 */

public class MyIntentService extends IntentService {

    /**
     * 首先要提供一个无参构造函数,在其内部调用其父类的有参构造函数
     */
    public MyIntentService() {

        super("MyIntentService"); //调用父类的有参构造函数
        //打印当前线程的id
    }

    /**
     * 在抽象的onHandleIntent()这个方法中可以去处理一些具体的逻辑,不用担心ANR问题,
     * 因为这个方法已经是在子线程中运行的了
     * @param intent
     */
    @Override
    protected void onHandleIntent( Intent intent) {

        //打印当前线程的id
        Log.d("MyIntentService","Thread is "+Thread.currentThread().getId());
    }
    public void onDestory(){
        super.onDestroy();
        Log.d("MyIntentService","onDestory executed");
        Toast.makeText(this,"Thread is is"+Thread.currentThread().getId(),Toast.LENGTH_SHORT).show();
    }
}

MyService.java

package lbstest.example.com.lbs.ServiceTest;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.IBinder;
import android.support.v7.app.NotificationCompat;
import android.util.Log;

import lbstest.example.com.lbs.R;

/**
 * Created by bummer on 2017/7/26.
 */

public class MyService extends Service {

    private DownloadBinder mBinder = new DownloadBinder();

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("MyService","onCreate executed");
        Intent intent = new Intent(this,Main3Activity.class);
        PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);
        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("This is content title")
                .setContentText("This is content text")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                .setContentIntent(pi)
                .build();
        startForeground(1,notification); //将MyService变成一个前台服务,并在系统状态栏显示出来
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("MyService", "onStartCommand executed");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("MyService", "onDestroy executed");
    }


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

    class DownloadBinder extends Binder {
        public void startDownload() {
            Log.d("Myservice", "startDownload executed");
        }

        public int getProgress() {
            Log.d("MyService", "getProgress");
            return 0;
        }

        public IBinder onBind(Intent intent) {
            return mBinder;
        }

    }


}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/start_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="start_service" />

    <Button
        android:id="@+id/stop_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="stop_service" />

    <Button
        android:id="@+id/bing_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Bind Service" />

    <Button
        android:id="@+id/unbing_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Unbind Service" />
    <Button
        android:id="@+id/start_intent_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="start_intent_service" />

</LinearLayout>
原文地址:https://www.cnblogs.com/CCCrunner/p/11781909.html