protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stop = (Button) findViewById(R.id.stop);
start = (Button) findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this , MyService.class);
startService(intent); //启动服务
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent stopIntent = new Intent(MainActivity.this , MyService.class);
stopService(stopIntent); //停止服务
}
});
}
public class MyService extends Service {//需要在manifest文件中注册
//自身调用stopself()也可以停止服务运行
public MyService() {
}
@Override
public void onCreate() { //第一次服务创建时调用,已经创建了就直接onstartcommand()
super.onCreate();
Log.i("mydate" , "oncreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) { //服务启动时调用
Log.i("mydate" , "onstartcommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() { //服务销毁时调用
Log.i("mydate" , "ondestroy");
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
/*// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");*/
return (new MyBinder()); //具体干嘛,做什么 ,如果没有指定干嘛的话就为空
}
class MyBinder extends Binder { //活动指挥服务干嘛,做什么什么,需要这个东西决定具体做什么
public void startDownload(){
Log.i("mydate" , "开始下载");
}
//...
}
}
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"></service>
使用onBind()方法
@Override
public IBinder onBind(Intent intent) {
/*// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");*/
return (new MyBinder()); //具体干嘛,做什么 ,如果没有指定干嘛的话就为空
}
public class MainActivity extends AppCompatActivity {
private Button stop;
private Button start;
private MyService.MyBinder myBinder; //指挥服务具体干嘛的
private ServiceConnection connection = new ServiceConnection() { //对开启服务进行包装,使其具体干吗,做什么,什么
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
myBinder = (MyService.MyBinder) service;
myBinder.startDownload(); //具体调用这个方法
//...
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stop = (Button) findViewById(R.id.stop);
start = (Button) findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this , MyService.class);
bindService(intent , connection , BIND_AUTO_CREATE); //绑定服务 指定binder 已经开启了服务,则不在执行这个语句
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent stopIntent = new Intent(MainActivity.this , MyService.class);
unbindService(connection); //解绑服务
}
});
}
}