service与activity都是从Context派生出来。
先看service的生命周期:
通过代码看service的几种形式:
1首先,最简单的形式直接启动service;
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this,"myService start",Toast.LENGTH_SHORT).show();
return START_STICKY;
}
}
2通过bindService()启动service;
public class BindService extends Service {
private IBinder binder=new LocalBinder();
public BindService() {
}
public class LocalBinder extends Binder {
BindService getService(){
return BindService.this;
}
}
public IBinder onBind(Intent intent){
return binder;
}
public String getString(){
return "suceessful !!!";
}
}
3通过intentService;其中intentService是运行另外一个线程,而前面的两个是运行在主线程的;
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
System.out.println("IntentService start");
}
}
看主测试类,这里要注意下bindService的用法;
public class MainActivity extends AppCompatActivity {
Button btnService,btnIntentService,bindService;
BindService mService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnService=(Button)findViewById(R.id.service);
btnIntentService=(Button)findViewById(R.id.IntentService);
bindService=(Button)findViewById(R.id.bindService);
btnService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(),MyService.class);
startService(intent);
}
});
btnIntentService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent1 = new Intent(getApplicationContext(), MyIntentService.class);
startService(intent1);
}
});
bindService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplication(),mService.getString(),Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onStart(){
super.onStart();
Intent intent = new Intent(getApplicationContext(), BindService.class);
bindService(intent, mConnection, getApplicationContext().BIND_AUTO_CREATE);
}
private ServiceConnection mConnection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
BindService.LocalBinder binder=(BindService.LocalBinder)service;
mService=binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
}