第19天Service-IntentService
阿新 • • 發佈:2018-12-18
第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);
}
}
}
}