Service的启动方式以及生命周期
public class MyService extends Service {
private static final String TAG = "MyService" ;
public MyService ( ) {
Log. i ( TAG, "MyService: 不好..被创建了" ) ;
}
@Override
public IBinder onBind ( Intent intent) {
Log. i ( TAG, "onBind: 绑啥绑" ) ;
return null;
}
}
XML布局
< ? xml version= "1.0" encoding= "utf-8" ? >
< LinearLayout xmlns: android= "http://schemas.android.com/apk/res/android"
xmlns: app= "http://schemas.android.com/apk/res-auto"
xmlns: tools= "http://schemas.android.com/tools"
android: layout_width= "match_parent"
android: orientation= "vertical"
android: layout_height= "match_parent"
tools: context= ".MainActivity" >
< Button
android: layout_width= "wrap_content"
android: layout_height= "wrap_content"
android: id= "@+id/create_server_id"
android: text= "启动一个服务"
/ >
< Button
android: layout_width= "wrap_content"
android: layout_height= "wrap_content"
android: id= "@+id/stop_server_id"
android: text= "停止一个服务"
/ >
< / LinearLayout>
package com. example. month2to2;
import android. content. Intent;
import android. support. v7. app. AppCompatActivity;
import android. os. Bundle;
import android. view. View;
import android. widget. Button;
import com. example. month2to2. service. MyService;
public class MainActivity extends AppCompatActivity {
private Button createServerId;
private Button stopServerId;
private Intent intent;
@Override
protected void onCreate ( Bundle savedInstanceState) {
super . onCreate ( savedInstanceState) ;
setContentView ( R. layout. activity_main) ;
stopServerId = findViewById ( R. id. stop_server_id) ;
createServerId = findViewById ( R. id. create_server_id) ;
stopServerId. setOnClickListener ( new View. OnClickListener ( ) {
@Override
public void onClick ( View v) {
stopService ( intent) ;
}
} ) ;
createServerId. setOnClickListener ( new View. OnClickListener ( ) {
@Override
public void onClick ( View v) {
intent = new Intent ( MainActivity. this , MyService. class ) ;
startService ( intent) ;
}
} ) ;
}
}
绑定服务和解除绑定
public class MainActivity extends AppCompatActivity {
private Intent intent;
private MyService myService;
private ServiceConnection connection= new ServiceConnection ( ) {
@Override
public void onServiceConnected ( ComponentName name, IBinder service) {
Log. i ( TAG, "onServiceConnected: " ) ;
MyService. MyBinder binder = ( MyService. MyBinder) service;
binder. callShow ( ) ;
}
@Override
public void onServiceDisconnected ( ComponentName name) {
}
} ;
@Override
protected void onCreate ( Bundle savedInstanceState) {
super . onCreate ( savedInstanceState) ;
setContentView ( R. layout. activity_main) ;
intent = new Intent ( this , MyService. class ) ;
bindService ( intent, connection, Service. BIND_AUTO_CREATE) ;
}
@Override
protected void onDestroy ( ) {
super . onDestroy ( ) ;
unbindService ( connection) ;
}
public void jiehun ( View view) {
myService. jiehun ( ) ;
}
}