admin 管理员组文章数量: 887007
第十九天 Service和IntentService的使用
服务
- Service
- activity代码
- 通过系统自动生成的Service
- 维活服务
- 服务代码
- IntentService
- activity代码
- 自定义序列化GsonBean类
- 服务
Service
activity代码
package com.example.afternoon;import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;import com.example.afternoon.MyService.MyService;public class MainActivity extends AppCompatActivity {private ServiceConnection sc;private static final String TAG = "MainActivity";private MyService.MyBinder mb;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}public void click(View view) {Intent it = new Intent(MainActivity.this, MyService.class);switch( view.getId()) {case R.id.button_bind:sc = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {Log.i(TAG, "onServiceConnected: ");mb= (MyService.MyBinder) service;mb.callStart();mb.callStop();}@Overridepublic void onServiceDisconnected(ComponentName name) {}};bindService(it,sc, Service.BIND_AUTO_CREATE);break;case R.id.button_unbind:unbindService(sc);break;case R.id.button_start:startService(it);break;case R.id.button_stop:stopService(it);break;case R.id.button_bind_start:mb.callStart();break;case R.id.button_bind_stop:mb.callStop();break;}}@Overrideprotected void onDestroy() {super.onDestroy();if (sc!=null) {unbindService(sc);}}
}
通过系统自动生成的Service
package com.example.afternoon.MyService;import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;public class MyService extends Service {private static final String TAG = "MyService";public MyService() {}@Overridepublic IBinder onBind(Intent intent) {// TODO: Return the communication channel to the service.Log.i(TAG, "onBind: ");return new MyBinder();}@Overridepublic void onCreate() {super.onCreate();Log.i(TAG, "onCreate: ");}@Overridepublic void onDestroy() {super.onDestroy();Log.i(TAG, "onDestroy: ");}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.i(TAG, "onStartCommand: ");return super.onStartCommand(intent, flags, startId);}@Overridepublic boolean onUnbind(Intent intent) {Log.i(TAG, "onUnbind: ");return super.onUnbind(intent);}public class MyBinder extends Binder{public void callStart( ){start( );}public void callStop( ){stop();}private void stop() {Log.i(TAG, "stop: stop");}private void start() {Log.i(TAG, "start: start");}}
}
维活服务
package com.example.afternoon;import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;import com.example.afternoon.MusicService.MusicService;public class MusicActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_music);Intent it = new Intent(this, MusicService.class);startService(it);}
}
服务代码
package com.example.afternoon.MusicService;import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;import com.example.afternoon.MainActivity;
import com.example.afternoon.R;public class MusicService extends Service {public MusicService() {}@Overridepublic void onCreate() {super.onCreate();}@Overridepublic IBinder onBind(Intent intent) {// TODO: Return the communication channel to the service.throw new UnsupportedOperationException("Not yet implemented");}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Notification.Builder builder = new Notification.Builder(getApplicationContext());builder.setSmallIcon(R.mipmap.ic_launcher_round).setContentTitle("音乐播放器").setContentText("这是我的内容。");Intent it = new Intent(getApplicationContext(), MainActivity.class);PendingIntent activity = PendingIntent.getActivity(getApplicationContext(), 102, it, PendingIntent.FLAG_UPDATE_CURRENT);builder.setContentIntent(activity);Notification build = builder.build();//id随意,通知对象。 设置在前台启动。startForeground(110,build);return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {// 停止前台服务--参数:表示是否移除之前的通知stopForeground(true);super.onDestroy();}
}
IntentService
实现网络获取数据并且添加到listview
activity代码
包含一个内部类广播
实现了获取GsonBean对象并且设置到ListView
package com.example.ecening.ep1;import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;import com.example.ecening.R;import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;public class mp1_activity extends AppCompatActivity{private Intent it;private MyBroaddCast mbc;private ListView lv;private List<String> str;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_mp1_activity);lv=findViewById(R.id.ep1_main_list);IntentFilter itf = new IntentFilter();itf.addAction("com.819.ep1");mbc = new MyBroaddCast();registerReceiver(mbc,itf);it = new Intent(this, MyIntentService.class);startService(it);lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position, long id) {Toast.makeText(mp1_activity.this, str.get(position), Toast.LENGTH_SHORT).show();}});}@Overrideprotected void onDestroy() {super.onDestroy();stopService(it);unregisterReceiver(mbc);}class MyBroaddCast extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) {str=new ArrayList<>();if( intent.getAction().equals("com.819.ep1")){Bundle bun = intent.getExtras();MyGson list = (MyGson) bun.getSerializable("list");List<MyGson.DataBean> data = list.getData();for (int i = 0; i < data.size(); i++) {str.add(data.get(i).getTitle());}ArrayAdapter arrayAdapter = new ArrayAdapter(mp1_activity.this, R.layout.support_simple_spinner_dropdown_item, str);lv.setAdapter(arrayAdapter);Toast.makeText(context, list.toString(), Toast.LENGTH_SHORT).show();}}}
}
自定义序列化GsonBean类
通过Intent的putExtras方法传递Bundle的序列化对象。
package com.example.ecening.ep1;import java.io.Serializable;
import java.util.List;public class MyGson implements Serializable {/*** ret : 1* data : [{"id":"8289","title":"油焖大虾","pic":".jpg","collect_num":"1669","food_str":"大虾 葱 生姜 植物油 料酒","num":1669},{"id":"2127","title":"四川回锅肉","pic":".jpg","collect_num":"1591","food_str":"猪肉 青蒜 青椒 红椒 姜片","num":1591},{"id":"30630","title":"超简单芒果布丁","pic":".jpg","collect_num":"1542","food_str":"QQ糖 牛奶 芒果","num":1542},{"id":"9073","title":"家常红烧鱼","pic":".jpg","collect_num":"1425","food_str":"鲜鱼 姜 葱 蒜 花椒","num":1425},{"id":"10097","title":"家常煎豆腐","pic":".jpg","collect_num":"1418","food_str":"豆腐 新鲜红椒 青椒 葱花 油","num":1418},{"id":"10509","title":"水煮肉片","pic":".jpg","collect_num":"1341","food_str":"瘦猪肉 生菜 豆瓣酱 干辣椒 花椒","num":1341},{"id":"46968","title":"红糖苹果银耳汤","pic":".jpg","collect_num":"1252","food_str":"银耳 苹果 红糖","num":1252},{"id":"10191","title":"麻婆豆腐","pic":".jpg","collect_num":"1221","food_str":"豆腐 肉末 生抽 白糖 芝麻油","num":1221},{"id":"2372","title":"皮蛋瘦肉粥","pic":".jpg","collect_num":"1151","food_str":"大米 皮蛋 猪肉 油条 香葱","num":1151},{"id":"2166","title":"蚂蚁上树","pic":".jpg","collect_num":"1144","food_str":"红薯粉 肉 姜 蒜 花椒","num":1144},{"id":"2262","title":"糖醋肉","pic":".jpg","collect_num":"1078","food_str":"猪肉 红椒 黄椒 洋葱 蛋清","num":1078},{"id":"9971","title":"鱼香豆腐","pic":".jpg","collect_num":"1010","food_str":"豆腐 木耳 胡萝卜 香葱 番茄酱","num":1010},{"id":"10172","title":"干煸四季豆","pic":".jpg","collect_num":"992","food_str":"四季豆 干辣椒 蒜头 酱油 糖","num":992},{"id":"2685","title":"胡萝卜肉末蒸蛋","pic":".jpg","collect_num":"926","food_str":"胡萝卜 肉 蛋 生抽 盐","num":926},{"id":"9972","title":"虎皮青椒","pic":".jpg","collect_num":"892","food_str":"青辣椒 大蒜 香醋 白糖 生抽","num":892},{"id":"10437","title":"叉烧排骨","pic":".jpg","collect_num":"803","food_str":"排骨 李锦记叉烧酱 植物油 清水 油菜","num":803},{"id":"2892","title":"\u201c五行\u201d彩蔬汤","pic":".jpg","collect_num":"760","food_str":"黑木耳 玉米 牛蒡 胡萝卜 西兰花","num":760},{"id":"2348","title":"麻辣肉丝面","pic":".jpg","collect_num":"758","food_str":"面条 肉丝 淀粉 酱油 辣椒","num":758},{"id":"33783","title":"美人豆浆","pic":".jpg","collect_num":"757","food_str":"黄豆 红豆 绿豆 黑豆 黑米","num":757},{"id":"10044","title":"土豆炖翅根","pic":".jpg","collect_num":"756","food_str":"土豆 翅根 葱 姜 料酒","num":756}]*/private int ret;private List<DataBean> data;public int getRet() {return ret;}public void setRet(int ret) {this.ret = ret;}public List<DataBean> getData() {return data;}public void setData(List<DataBean> data) {this.data = data;}public static class DataBean implements Serializable {/*** id : 8289* title : 油焖大虾* pic : .jpg* collect_num : 1669* food_str : 大虾 葱 生姜 植物油 料酒* num : 1669*/private String id;private String title;private String pic;private String collect_num;private String food_str;private int num;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getPic() {return pic;}public void setPic(String pic) {this.pic = pic;}public String getCollect_num() {return collect_num;}public void setCollect_num(String collect_num) {this.collect_num = collect_num;}public String getFood_str() {return food_str;}public void setFood_str(String food_str) {this.food_str = food_str;}public int getNum() {return num;}public void setNum(int num) {this.num = num;}}
}
服务
包含网络请求数据
package com.example.ecening.ep1;import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.os.Bundle;
import android.os.Message;import com.google.gson.Gson;import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.HttpURLConnection;
import java.MalformedURLException;
import java.URL;
import java.URLConnection;
import java.util.List;public class MyIntentService extends IntentService implements Serializable {public MyIntentService() {super("MyIntentService");}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {return super.onStartCommand(intent, flags, startId);}@Overrideprotected void onHandleIntent(Intent intent) {try {URL url=new URL( ".php?stage_id=1&limit=20&page=1");HttpURLConnection uc = (HttpURLConnection) url.openConnection();uc.connect();if( uc.getResponseCode()==200){StringBuffer sb = new StringBuffer();InputStream is = uc.getInputStream();int len=0;byte[] arr=new byte[1024];while( (len=is.read(arr))!=-1){sb.append(new String( arr,0,len));}Gson gson = new Gson();MyGson myGson = gson.fromJson(sb.toString(), MyGson.class);List<MyGson.DataBean> data = myGson.getData();Bundle bundle = new Bundle();bundle.putSerializable("list",myGson);Intent it = new Intent();it.setAction("com.819.ep1");it.putExtras(bundle);sendBroadcast(it);is.close();}uc.disconnect();} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
}
本文标签: 第十九天Service和IntentService的使用
版权声明:本文标题:第十九天Service和IntentService的使用 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.freenas.com.cn/jishu/1732356042h1534461.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论