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"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值