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("<---------->","任务结束"); } }