張萌&韓墨羽——後臺操作及IntentService

後臺操作及IntentService

IntentService介紹

在這裏插入圖片描述

IntentService 是service的子類, 已經現實了.onbind的方法.我們只要重寫其中的 onHandleIntent即可.

IntentService 是繼承自 Service 並處理異步請求的一個類,在 IntentService
內有一個工作線程來處理耗時操作。
當任務執行完後,IntentService 會自動停止,不需要我們去手動結束。
如果啓動 IntentService 多次,那麼每一個耗時操作會以工作隊列的方式在 IntentService 的
onHandleIntent 回調方法中執行,依次去執行,使用串行的方式,執行完自動結束。

使用IntentService網絡請求json串,將json串使用廣播發送給activity界面

思路:創建服務,註冊服務 ,

(1)創建服務:MyIntentService.java

public class MyIntentService extends IntentService {
    //TODO  注意:必須提供無參數構造,不然清單文件中註冊報錯
    public MyIntentService(){
        super("MyIntentService");
    }

    public MyIntentService(String name) {
        super(name);
    }
    //TODO  將所有耗時操作都在該方法中完成,相當於開啓線程
    @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));
                }
                //TODO 向Activity或Fragment發送json串
                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();
            }
        }
    }
}

(2)清單文件註冊服務

 <service android:name=".Intentservice.MyIntentService" />

(3)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", "");
                //接續json串 展現在ListView 中
                Toast.makeText(context, ""+json, Toast.LENGTH_SHORT).show();

            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章