android 本地service使用

直接上码简单易懂


package com.example.day601;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

/**
 * 后台播放···网络音频   采用service来实现
 * 本地Service  远程Service
 * 此处如果将Service实现为内部类将会出现"has no paramer constructor"
 *
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private Button start,stop;//开启关闭service
    private Intent serviceIntent;//启动service所需Intent
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        start=(Button)findViewById(R.id.start);
        stop=(Button)findViewById(R.id.stop);

        serviceIntent=new Intent(this,SimpleServiceIntent.class);
        start.setOnClickListener(this);
        stop.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v == start) {
            startService(serviceIntent);    //点击start后一次调用onCreate()  onStartCommand()
        } else if (v == stop) {
            stopService(serviceIntent);
        }
    }

}


package com.example.day601;

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

public class SimpleServiceIntent extends Service {
    public SimpleServiceIntent() {
    }
    /**
     * @param intent
     * @return null
     * 没有需要绑定的任务,该方法返回null
     */
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    /**
     * 实例化Service时调用
     */
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("Service", "onCreate");
    }
    /**
     * @param intent
     * @param flags
     * @param startId
     * @return START_STICKY表明如果结束了该服务,那么将重新启动该服务
     * android 2.0后引入了该方法  每当调用startService时就会调用该方法
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//            return super.onStartCommand(intent, flags, startId);
        Log.i("Service", "onStartCommand");
        return START_STICKY;
    }
    /**
     * @param intent
     * @param startId 2.0之前的版本调用该onStart方法
     */
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.i("Service", "onStart");
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("Service", "onDestroy");
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值