Android Studio Service service (one of the four components)

Service

Characteristic

No interface, running in the background

How to create

Custom class inherits Service
Rewrite onBind
Registration (manifest file)
Lifecycle oncreate() - onstartcommand - ondestore()
Starting mode
startService() -stopService(); it runs in the background all the time after startup, unless it is not related to Activity
Bindservice() - anbindservice(); when activity exits and the service is closed, you can call the method used by the service
Binding service steps
Create service
Override onBind(){new binder()}
Create binder

Code snippet implementation background network download json string

Http download tool class string is optional

public class HttpUtils {
    public static List<HashMap<String, String>> openUrl(String url){

        try {
            URL url1 = new URL(url);
            HttpURLConnection urlConnection = (HttpURLConnection) url1.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();
            if (urlConnection.getResponseCode() == 200) {
                InputStream is = urlConnection.getInputStream();
                byte[] bytes = new byte[1024];
                int len = 0;
                StringBuilder sb = new StringBuilder();
                while ((len = is.read(bytes)) != -1) {
                    String s = new String(bytes, 0, len);
                    sb.append(s);
                }
                String json = sb.toString();
                Gson gson = new Gson();
                JavaBean javaBean = gson.fromJson(json, JavaBean.class);
                List<JavaBean.DataBean> data = javaBean.getData();

                List<HashMap<String, String>> list = new ArrayList<>();

                for (int i = 0; i < data.size(); i++) {
                    JavaBean.DataBean dataBean = data.get(i);
                    String title = dataBean.getTitle();
                    String food = dataBean.getFood_str();
                    String pic = dataBean.getPic();

                    HashMap<String, String> map = new HashMap<>();
                    map.put("title", title);
                    map.put("food", food);
                    map.put("pic", pic);
                    list.add(map);
                }
                return list;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Customized server

public class MyService extends Service {
    String url = "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1";

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    public class MyBinder extends Binder {
        public MyService getMyService() {
            return MyService.this;
        }
    }

    public List<HashMap<String, String>> getMethod(){
        try {
            List<HashMap<String, String>> list = new MyService.MyAsyncTask().execute(url).get();
            return list;
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static class MyAsyncTask extends AsyncTask<String,Void,List<HashMap<String,String>>>{

        @Override
        protected List<HashMap<String, String>> doInBackground(String... strings) {
            return HttpUtils.openUrl(strings[0]);
        }
    }
}

Main class

public class MainActivity extends AppCompatActivity {
    Intent intent;
    MyService fuwu;
    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            fuwu = ((MyService.MyBinder)service).getMyService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        intent = new Intent(MainActivity.this,MyService.class);
        bindService(intent,connection, Service.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
    }

    public void btn(View view) {
        List<HashMap<String, String>> list = fuwu.getMethod();
        Log.e("###",list.toString());
    }
}

Keywords: JSON network iOS PHP

Added by MikeSnead on Sun, 03 Nov 2019 23:46:56 +0200