IntentService
IntentService与Service区别
IntentService是Service的子类。Service运行在主线程,而IntentService为异步运行。Service运行结束后不会自动停止 服务,IntentService执行完任务后会自动销毁。举例,如果我们想要实现后台下载Json串这个任务,用Service的话,需要自己写个子线程。用IntentService就不需要手写子线程,因为它本身就是异步。
创建IntentService
下载Json串案例
界面
效果
public class MyIntentService extends IntentService {
HttpURLConnection connection;
InputStream inputStream;
public MyIntentService(){
super("anyway");
}
public MyIntentService(String name) {
super(name);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
try {
URL url = new URL("http://c.m.163.com/nc/article/headline/T1348647853363/0-40.html");
connection = (HttpURLConnection) url.openConnection();
inputStream = connection.getInputStream();
byte[] bytes = new byte[1024];
int len = 0;
StringBuffer stringBuffer = new StringBuffer();
while ((len = inputStream.read(bytes)) != -1){
stringBuffer.append(new String(bytes,0,len));
}
Intent intent1 = new Intent("com.intentreceiver");
intent1.putExtra("json",stringBuffer.toString());
sendBroadcast(intent1);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Activity.java
public class IntentServiceActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent_service);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(new String[]{Manifest.permission.INTERNET},1);
}
//注册广播接收者
registerReceiver(new IntentReceiver(),new IntentFilter("com.intentreceiver"));
}
public void download(View view) {
//开启服务
Intent intent = new Intent(this,MyIntentService.class);
startService(intent);
}
/**
* 下载Json的广播接收者
*/
public class IntentReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
String json = intent.getStringExtra("json");
Log.d("amy",json);
}
}
}
表单文件
<service android:name=".MyIntentService"/>