您的位置:首页 > 移动开发

Service1

2016-01-11 11:48 316 查看
原来 service 是指界面被关掉 还能继续运行的意思,运行在后台。

startservice

stopservice

绑定服务(关闭界面,会退出当前的app)

bindservice

unbindservice

基本用法如下:

package zhbit.test;

import android.app.Activity;

import android.content.ComponentName;

import android.content.Context;

import android.content.Intent;

import android.content.ServiceConnection;

import android.os.Bundle;

import android.os.IBinder;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.Toast;

public class Using_ServiceActivity extends Activity implements OnClickListener, ServiceConnection {

/* Called when the activity is first created. /

private Button btnstartservice, btnstopservice, btnbindservice,

btnunbindservice;

private Intent intent1;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

intent1 = new Intent(Using_ServiceActivity.this, Second.class);

btnstartservice = (Button) findViewById(R.id.StartService);
btnstopservice = (Button) findViewById(R.id.stopService);
btnbindservice = (Button) findViewById(R.id.BindService);
btnunbindservice = (Button) findViewById(R.id.UnBindService);
btnstartservice.setOnClickListener(this);
btnstopservice.setOnClickListener(this);
btnbindservice.setOnClickListener(this);
btnunbindservice.setOnClickListener(this);

}

public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.StartService:
startService(intent1);
break;
case R.id.stopService:
stopService(intent1);
break;
case R.id.BindService:
bindService(intent1, this, Context.BIND_AUTO_CREATE);
break;
case R.id.UnBindService:
unbindService(this);
//  stopService(intent1);
break;

default:
break;
}
}

public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
Toast.makeText(this, "onserviceconnected", Toast.LENGTH_LONG).show();
}

public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
Toast.makeText(this, "onservicedisconnected", Toast.LENGTH_LONG).show();
}


}

package zhbit.test;

import android.app.Service;

import android.content.Intent;

import android.os.Binder;

import android.os.IBinder;

import android.widget.Toast;

public class Second extends Service{

@Override
public void onCreate() {

Toast.makeText(this, "onCreate", Toast.LENGTH_LONG).show();
System.out.print("onCrate");
super.onCreate();
}

@Override
public void onDestroy() {
Toast.makeText(this, "onDestroy", Toast.LENGTH_LONG).show();
System.out.print("onDestroy");
super.onDestroy();
}
private final EchServiceBinder echservicebinder = new EchServiceBinder();
public class EchServiceBinder extends Binder{

}
@Override
public IBinder onBind(Intent intent) {
Toast.makeText(this, "onBind", Toast.LENGTH_LONG).show();
return echservicebinder;
}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  app