安卓四大组件之Sevice组件的简单使用 --Android基础

1、本例实现了简单的Service(服务)的创建、启动和停止,点击“启动SERVICE”页面会显示“服务被创建”,接着是“服务被启动”。点击“停止SERVICE”页面提示“服务被停止”。太过基础,直接贴代码了……新手看看,老司机就忽略吧……

2、基本代码

ServiceDemo:

package thonlon.example.cn.servicedemo;

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

/**
* 绑定服务的时候被调用
*/
public class ServiceDemo extends Service {
  @Nullable
  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

/**
* Service被创建后被调用
*/
  @Override
  public void onCreate() {
    Toast.makeText(ServiceDemo.this,"服务被创建",Toast.LENGTH_SHORT).show();
    Log.d("onCreate", "服务被创建");
  }

/**
* Service被开始后调用
*
* @param intent
* @param flags
* @param startId
* @return
*/
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(ServiceDemo.this,"服务被启动",Toast.LENGTH_SHORT).show();
    Log.d("onStartCommand", "服务被启动");
    return super.onStartCommand(intent, flags, startId);
  }

/**
* Service被停止后调用
*/
  @Override
  public void onDestroy() {
    Toast.makeText(ServiceDemo.this,"服务被停止",Toast.LENGTH_SHORT).show();
    Log.d("onDestroy", "服务被停止");
  }
}

MainActivity:

package thonlon.example.cn.servicedemo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
  }
  public void onClick(View v){
    Intent intent = new Intent();
    intent.setClass(this,ServiceDemo.class);
    switch (v.getId()){
      case R.id.btn_start_service://第一次点启动Service,服务会被创建,之后再点击启动服务不会再被创建,服务已经被创建
        startService(intent);
        break;
      case R.id.btn_stop_service:
        stopService(intent);
        break;
    }
  }
}

posted @ 2018-06-15 09:49  牛新龙的IT技术博客  阅读(1172)  评论(0编辑  收藏  举报