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("<---------->","任务结束");
        }
    }
  • 相关阅读:
    css3
    css3
    npm 安装包无法继续下载? 卡住
    tcp/ip协议中的SYN, ACK的数值变化
    【转】6 Reasons Why JavaScript’s Async/Await Blows Promises Away (Tutorial)
    ES6 中 Symbol.split的用法
    Why does Typescript use the keyword “export” to make classes and interfaces public?
    es6中的import,export浏览器已经支持
    Understanding the JavaScript Engine—— two phase
    【转】js-ES6学习笔记-Symbol
  • 原文地址:https://www.cnblogs.com/luckyplj/p/10522742.html
Copyright © 2011-2022 走看看