Android Studio 1-15 IntentService

Android Studio 1-15 IntentService

  • 案例
    • Acticity
    • 广播
    • 服务
    • 适配器

案例

##主界面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ex3.Main3Activity">

    <ListView
        android:id="@+id/listview_main3"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>

</LinearLayout>

Acticity

package com.example.day14ex.ex3;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.day14ex.R;
import com.example.day14ex.ex1.MyService;

import java.util.ArrayList;
import java.util.List;

public class Main3Activity extends AppCompatActivity {

    private static final String TAG = "Main3Activity";
    private MyReceiver myReceiver;
    private Intent intent;
    private MyAdapter myAdapter;
    private ListView listviewMain3;
    private List<Bean.DataBean> data = new ArrayList<>();
    private Handler handler = new Handler(){

    };

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

        listviewMain3 = (ListView) findViewById(R.id.listview_main3);

        //动态注册广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("ex3.MyIntentService");
        myReceiver = new MyReceiver(handler,listviewMain3,data);
        registerReceiver(myReceiver,intentFilter);
        //开启一个服务
        intent = new Intent(this, MyIntentService.class);
        startService(intent);

//        listviewMain3.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView adapterView, View view, int i, long l) {
//                Toast.makeText(Main3Activity.this, ""+data.get(i).getTitle(), Toast.LENGTH_SHORT).show();
//            }
//        });

    }

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

广播

package com.example.day14ex.ex3;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.List;

public class MyReceiver extends BroadcastReceiver {

    private static final String TAG = "MyReceiver";

    private Handler handler;
    private ListView listView;
    private MyAdapter myAdapter;
    private List<Bean.DataBean> data;

    public MyReceiver(Handler handler, ListView listView) {
        this.handler = handler;
        this.listView = listView;
    }

    public MyReceiver(Handler handler, ListView listView, List<Bean.DataBean> data) {
        this.handler = handler;
        this.listView = listView;
        this.data = data;
    }

    @Override
    public void onReceive(final Context context, Intent intent) {
        String action = intent.getAction();
        Log.i(TAG, "onReceive: "+action);
        if ("ex3.MyIntentService".equals(action)) {
            Bundle bundle = intent.getExtras();
            String json = bundle.getString("json", "");
            //接续json串 展现在ListView 中
            Log.i(TAG, "onReceive: " + json);
//            Toast.makeText(context, "" + json, Toast.LENGTH_SHORT).show();

            data = new Gson().fromJson(json, Bean.class).getData();
            myAdapter = new MyAdapter(context,data);

            handler.post(new Runnable() {
                @Override
                public void run() {
                    listView.setAdapter(myAdapter);
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            Toast.makeText(context, ""+data.get(i).getTitle(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });

        }
    }

}

服务

package com.example.day14ex.ex3;

import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.os.Bundle;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

public class MyIntentService extends IntentService {

    public MyIntentService() {
        super("MyIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        InputStream is = null;
        ByteArrayOutputStream baos = null;
        HttpURLConnection connection = 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.setRequestMethod("GET");
            connection.setReadTimeout(2*1000);
            connection.setConnectTimeout(2*1000);
            connection.connect();
            if (connection.getResponseCode() == 200){
                is = connection.getInputStream();
                baos = new ByteArrayOutputStream();
                byte[] bytes = new byte[2048];
                int len;
                while ((len = is.read(bytes)) != -1){
                    baos.write(bytes,0, len);
                }

                Intent intent1 = new Intent();
                intent1.setAction("ex3.MyIntentService");
                Bundle bundle = new Bundle();
                bundle.putString("json",baos.toString());
                intent1.putExtras(bundle);
                sendBroadcast(intent1);
//                startActivity(intent1);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

适配器

package com.example.day14ex.ex3;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.day14ex.R;

import java.util.List;

public class MyAdapter extends BaseAdapter {
    private Context context;
    private List<Bean.DataBean> beanList;
    private LayoutInflater layoutInflater;

    public MyAdapter(Context context, List<Bean.DataBean> beanList) {
        this.context = context;
        this.beanList = beanList;
        layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return beanList.size();
    }

    @Override
    public Object getItem(int i) {
        return beanList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHoder viewHoder;
        if (view == null){
            view = layoutInflater.inflate(R.layout.layout_item,viewGroup,false);
            viewHoder = new ViewHoder();
            viewHoder.imageView = view.findViewById(R.id.iv_item);
            viewHoder.textView = view.findViewById(R.id.tv_item);
            view.setTag(viewHoder);
        }else {
            viewHoder = (ViewHoder) view.getTag();
        }

        Glide.with(context).load(beanList.get(i).getPic()).into(viewHoder.imageView);
        viewHoder.textView.setText(beanList.get(i).getTitle());

        return view;
    }


    private class ViewHoder {
        private ImageView imageView;
        private TextView textView;
    }
}

你可能感兴趣的:(学习)