service启动和停止,绑定和解除绑定

service的作用就是不和用户进行交互,比如网络连接,服务器推送

首先要创建一个service

package com.example.servicedemoone;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;

public class Myservice extends Service {

@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return new Binder();
//返回一个binder
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this, "启动", Toast.LENGTH_SHORT).show();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "停止", Toast.LENGTH_SHORT).show();
}
}

然后在配置文件里进行注册

<service
android:name="com.example.servicedemoone.Myservice"
android:enabled="true"
android:exported="false"
/>

最后通过点击按钮对servise进行启动和关闭

package com.example.servicedemoone;

import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener,
ServiceConnection {
private Button btn_start;
private Button btn_stop;
private Button btn_bind;
private Button btn_unbind;
private Intent intent;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_start = (Button) findViewById(R.id.btn_start);
btn_stop = (Button) findViewById(R.id.btn_stop);
btn_bind = (Button) findViewById(R.id.btn_bind);
btn_unbind = (Button) findViewById(R.id.btn_unbind);
intent = new Intent(MainActivity.this, Myservice.class);
btn_start.setOnClickListener(this);
btn_stop.setOnClickListener(this);
btn_bind.setOnClickListener(this);
btn_unbind.setOnClickListener(this);

}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_start:
startService(intent);
break;
case R.id.btn_stop:
stopService(intent);
break;
case R.id.btn_bind:
//绑定服务,传入的参数分别是intent,服务的连接,这时候需要实现一个
//ServiceConnection,最后一个是固定的
bindService(intent, this, Context.BIND_AUTO_CREATE);

break;


case R.id.btn_unbind:
//解除绑定,传入的参数也是服务连接,也要实现ServiceConnection
unbindService(this);
break;
}
}

@Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
// 服务被绑定成功后调用
Log.d("msg", "service conn");
}

@Override
public void onServiceDisconnected(ComponentName arg0) {
//服务所在进程崩溃时调用,或者说杀掉时候调用

}

}

 service开始启动的时候会执行oncreate(),销毁的时候会执行ondestory();onStartCommand会不断的被执行

原文地址:https://www.cnblogs.com/84126858jmz/p/4869685.html