Services实现效果:
开启服务方法:
startService(intent);
关闭服务方法:
stopService(intent);
服务执行完毕后自动调用onDestroy方法
stopSelf();
//继承Service
package com.example.g160628_android_23_services1; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.SystemClock; import android.support.annotation.IntDef; import android.support.annotation.Nullable; import android.util.Log; import android.widget.ProgressBar; /** * Created by Administrator on 2017/7/14. */ public class MyServices extends Service { @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); Log.i("test","onCreate"); } @Override public int onStartCommand(Intent intent,int flags, int startId) { new MyThread(intent,startId).start(); Log.i("test","onStartCommand"); return Service.START_STICKY; } class MyThread extends Thread{ private int startId; private Intent intent; public MyThread(Intent intent,int startId){ this.startId=startId; this.intent=intent; } Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { int i=msg.what; MainActivity.progressBar.setProgress(i); } }; @Override public void run() { for (int i =1; i <=100 ; i++) { handler.sendEmptyMessage(i); SystemClock.sleep(200); Log.i("test"," "+i); } //服务执行完毕后自动调用onDestroy方法 stopSelf(startId); } } @Override public void onDestroy() { super.onDestroy(); Log.i("test","onDestroy"); } }
//主actitypackage com.example.g160628_android_23_services1; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ProgressBar; public class MainActivity extends AppCompatActivity { private Intent intent; public static ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); progressBar = (ProgressBar) findViewById(R.id.progressBar); intent = new Intent(this,MyServices.class); } //开始执行 public void start(View view){ startService(intent); } //关闭 public void stop(View view){ stopService(intent); }
}