zoukankan      html  css  js  c++  java
  • 034 Android IntentService 的使用

    1.service 执行耗时任务的步骤

    2.IntentService 

    (1)介绍

    (2)使用方法

    (3)优点

    (4)在AndroidManifest.xml文件中添加service设置

    <service android:name=".MyIntentService"></service>

    (5)java后台代码

    MainActivity主界面
    package com.lucky.test39intentservice;
    
    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    
    public class MainActivity extends AppCompatActivity {
        Button button1;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            button1=findViewById(R.id.button);
            button1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(MainActivity.this,MyIntentService.class);
                    startService(intent);//启动service
                }
            });
        }
    }

    MyIntentService

    package com.lucky.test39intentservice;
    
    import android.app.IntentService;
    import android.content.Intent;
    import android.util.Log;
    
    public class MyIntentService extends IntentService {
    
        //构造方法
        public MyIntentService() {
            super("");
        }
    
        //该方法会在service创建时,就执行
        @Override
        public void onCreate() {
            super.onCreate();
            Log.i("<----------->","任务启动");
        }
    
        //执行耗时任务
        @Override
        protected void onHandleIntent( Intent intent) {
            int count=100;
            while (count>0){
                Log.i("<---------->",count+"");
                count--;
                try {
                    Thread.sleep(500);  //对线程进行延时,模拟现实中执行的任务
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            Log.i("<---------->","任务结束");
        }
    }
  • 相关阅读:
    316. 去除重复字母
    331. 验证二叉树的前序序列化
    225. 用队列实现栈
    197. 上升的温度
    178. 分数排名
    177. 第N高的薪水
    小程序导航
    css3、js动画特效
    背景透明css
    h5新标签IE8不兼容怎么办?
  • 原文地址:https://www.cnblogs.com/luckyplj/p/10522742.html
Copyright © 2011-2022 走看看