AndroidManifest.xml
注册service
<service android:name=".service.myService" android:enabled="true" > <intent-filter> <action android:name="com.test.service" /> </intent-filter> </service>
Activity中启动服务(注:LocalService.class继承于Service)
方法1
//启动服务 Intent intent=new Intent(this,LocalService.class); startService(intent);
方法2
LocalService localService=null; //用bindService方法启动服务 private void BinderService(){ Intent intent=new Intent(this,LocalService.class); bindService(intent, new ServiceConnection(){ @Override public void onServiceConnected(ComponentName componentName, IBinder binder) { //调用bindService方法启动服务时候,如果服务需要与activity交互, //则通过onBind方法返回IBinder并返回当前本地服务 localService=((LocalService.LocalBinder)binder).getService(); //这里可以提示用户,或者调用服务的某些方法 } @Override public void onServiceDisconnected(ComponentName componentName) { localService=null; //这里可以提示用户 } }, Context.BIND_AUTO_CREATE); }
LocalService.java
时间: 2024-10-12 23:23:30