Service的两种启动方式+生命周期+IntentService的特点

Service服务

两种启动方式

  1. 启动方式
    开启服务:startService()
    停止服务:stopService()

  2. 绑定方式
    绑定服务:bindService()
    解除绑定:unbindService()

生命周期

  1. 启动方式的生命周期
    onCreate() —— onStartCommand() —— onDestroy()
  2. 绑定方式的生命周期
    onCreate() —— onBind() —— onUnbind() —— onDestroy()
  3. 先启动后绑定
    onCreate() —— onStartCommand() —— onBind() —— onUnbind() —— onDestroy()

StartService代码

  • 自定义类继承Service服务
public class MyService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this, "没毛病", Toast.LENGTH_SHORT).show();
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
  • 清单文件注册服务
<service android:name=".MyService"></service>
  • 启动或停止服务
public class MainActivity extends AppCompatActivity {
    private Intent intent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intent =new Intent(this,MyService.class);
        startService(intent);
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService(intent);
    }
}

bindService代码

  • 自定义类继承Service并在里面声明方法
public class MyService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }
    class MyBinder extends Binder{
        public MyService getService(){
            return MyService.this;
        }
    }
    public void show(){
        Toast.makeText(this, "没毛病", Toast.LENGTH_SHORT).show();
    }
}
  • 清单文件注册服务
<service android:name=".MyService"></service>
  • 绑定服务和解除绑定
public class MainActivity extends AppCompatActivity {
    private Intent intent;
    private MyService myService;
    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myService = ((MyService.MyBinder)service).getService();
        }
        @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 show(){
        myService.show();
    }
    
}

IntentService

IntentService的优点:不用开启线程,直接进行耗时操作
IntentService的缺点:使用广播向activity传值
IntentService代码

  • 自定义类继承IntentService并从网络下载
public class MyIntentService extends IntentService {
    public MyIntentService(){
        super("MyIntentService");
    }

    public MyIntentService(String name) {
        super(name);
    }
    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        StringBuffer sb=new StringBuffer();
        HttpURLConnection connection=null;
        InputStream inputStream=null;
        try {
            URL url=new URL("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1");
            connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(5*1000);
            connection.setConnectTimeout(5*1000);

            if(connection.getResponseCode()==200){
                inputStream  = connection.getInputStream();
                byte[] b=new byte[1024];
                int len=0;
                while((len=inputStream.read(b))!=-1){
                    sb.append(new String(b,0,len));
                }
                Intent intent1=new Intent();
                intent1.setAction("com.bawei.intentservice");
                Bundle bundle = new Bundle();
                bundle.putString("json",sb.toString());
                intent1.putExtras(bundle);
                sendBroadcast(intent1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null){
                connection.disconnect();
            }
        }
    }
}
  • 清单文件注册服务
 <service android:name=".Intentservice.MyIntentService" ></service>
  • Activity代码
public class MainActivity extends AppCompatActivity {
    private  MyReceiver myReceiver;
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction("com.bawei.intentservice");
        myReceiver=new MyReceiver();
        registerReceiver(myReceiver,intentFilter);
        intent=new Intent(this,MyIntentService.class);
        startService(intent);


    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
        stopService(intent);
    }

    class MyReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            String action=intent.getAction();
            if("com.bawei.intentservice".equals(action)){
                Bundle bundle = intent.getExtras();
                String json = bundle.getString("json", "");
                Toast.makeText(context, ""+json, Toast.LENGTH_SHORT).show();

            }
        }
    }
}

以上就是我所掌握的Service的两种启动方式+生命周期+IntentService的特点

你可能感兴趣的:(第一个月)