第19天Service-IntentService
IntentService
一.IntentService介绍
IntentService,可以看做是Service和HandlerThread的结合体,在完成了使命之后会自动停止,适合需要在工作线程处理UI无关任务的场景。
- IntentService 是继承自 Service 并处理异步请求的一个类,在 IntentService
内有一个工作线程来处理耗时操作。 - 当任务执行完后,IntentService 会自动停止,不需要我们去手动结束。
- 如果启动 IntentService 多次,那么每一个耗时操作会以工作队列的方式在 IntentService 的
onHandleIntent 回调方法中执行,依次去执行,使用串行的方式,执行完自动结束。
二.IntentService的优点:不用开启线程
三.IntentService的缺点:使用广播向activity传值
四.案例:使用IntentService网络请求json串,将json串使用广播发送给activity界面
(1)创建服务:MyIntentService.java
public class MyIntentService extends IntentService {
public MyIntentService(){
super("MyIntentService");
}
public MyIntentService(String name) {
super(name);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
//1.获取activity传来的值url
Bundle bundle= intent.getExtras();
StringBuffer sb=new StringBuffer();
String str=bundle.getString("url","");
try {
URL url=new URL(str);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
if(connection.getResponseCode()==200){
InputStream inputStream=connection.getInputStream();
byte[] b=new byte[1024];
int len=0;
while((len= inputStream.read(b))!=-1){
sb.append(new String(b,0,len));
}
//2.发送广播
Intent intent1= new Intent();
intent1.setAction("com.bawei");
Bundle bundle1=new Bundle();
bundle1.putString("json",sb.toString());
intent1.putExtras(bundle1);
sendBroadcast(intent1);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
(2)清单文件注册服务
<service android:name=".Intentservice.MyIntentService" />
(3)Activity代码
public class Main2Activity extends AppCompatActivity {
private MyReceiver registerReceiver;
private Intent intent;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
tv=findViewById(R.id.tv);
//TODO 注册广播
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction("com.bawei.1609A");
registerReceiver=new MyReceiver();
registerReceiver(registerReceiver,intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(registerReceiver);
stopService(intent);
}
public void getImage(View view) {
//开启服务
intent=new Intent(this,MyIntentService.class);
Bundle bundle=new Bundle();
bundle.putString("url","https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1545048588750&di=030cf1284c4cbf1fc1f6b20ce9e3899d&imgtype=0&src=http%3A%2F%2Fwww.jituwang.com%2Fuploads%2Fallimg%2F110715%2F9124-110G510051235.jpg");
startService(intent);
}
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action =intent.getAction();
if("com.bawei.1609A".equals(action)){
Bundle bundle=intent.getExtras();
String json=bundle.getString("json","");
Toast.makeText(context, ""+json, Toast.LENGTH_SHORT).show();
tv.setText(json);
}
}
}
}