这是服务里的代码
public class Myservice extends Service {
private DownloadBinder mBinder= new DownloadBinder();
@Override
public IBinder onBind(Intent intent){
return mBinder;
}
class DownloadBinder extends Binder{
public void startDownload(){
Log.d ( "MyService","startDownload excuted");
}
public int getProgress(){
Log.d("MyService","getprogress");
return 0;
}
}
@Override
public void onCreate(){
super.onCreate();
Log.d ( "MyService","OnCreate excuted");
}
@Override
public int onStartCommand(Intent intent,int flags,int startId){
Log.d ( "MyService","start excuted");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy(){
super.onDestroy();
Log.d ( "MyService","stop excuted");
}
}
这是主活动的代码
public class MainActivity extends ActionBarActivity implements OnClickListener {
private Button startService;
private Button stopService;
private Button bindService;
private Button unbindService;
private Myservice.DownloadBinder downloadBinder;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (Myservice.DownloadBinder) service;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService = (Button) findViewById(R.id.start_service);
stopService = (Button) findViewById(R.id.stop_service);
bindService = (Button) findViewById(R.id.bind_service);
unbindService = (Button) findViewById(R.id.unbind_service);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
bindService.setOnClickListener(this);
unbindService.setOnClickListener(this);
}
@Override
public void onClick(View v){
switch(v.getId()){
case R.id.start_service:
Intent startIntent = new Intent(this,Myservice.class);
startService(startIntent);break;
case R.id.stop_service:
Intent stopIntent = new Intent(this,Myservice.class);
stopService(stopIntent);break;
case R.id.bind_service:
Intent bindIntent = new Intent (this,Myservice.class);
bindService(bindIntent,connection,BIND_AUTO_CREATE);
break;
case R.id.unbind_service:
unbindService(connection);
break;
default:
break;
}
}
}
为什么DownloadBinder放在onStartCommand()后面然后点击bing_service会执行oncreate() 方法,放在oncreate则不会执行