Android基础12

service:服务。

  1. 开始服务
  2. 停止服务
  3. 通信,绑定活动
  4. 通信,解绑活动

新建service

package com.example.bbw.servicesdemo;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.util.Log;

public class MyService extends Service {

    private DownloadBinder binder = new DownloadBinder();

    public MyService() {
    }

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

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

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

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

     class DownloadBinder extends Binder{

        public void  startLoad(){
            Log.d("MyService","start Download");
        }

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

布局文件

开始服务

startServices.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent startIntent = new Intent(getApplicationContext(),MyService.class);
                startService(startIntent);
            }
        });

结束服务

stopServices.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent stopIntent = new Intent(getApplicationContext(),MyService.class);
                stopService(stopIntent);
            }
        });

你可能感兴趣的:(Android基础12)