service在后台运行
生命周期:onCreate()–>onStart()–>onDestroy()
1、新建一个service类
package com.example.wlb.launchlocalapp;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class MyService extends Service {
public MyService() {
}
private boolean serviceRunning = false;
@Override
public IBinder onBind(Intent intent) {
return new Binder();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("Service onCommand.");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
super.onCreate();
System.out.println("Service onCreate.");
serviceRunning = true;
new Thread(){
@Override
public void run() {
super.run();
while (serviceRunning) {
System.out.println("Service is running...");
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("Service onDestory.");
serviceRunning = false;
}
}
2、启动/停止Service
Intent intent = new Intent(MainActivity.this,MyService.class);
.....
startService(intent)
stopService(intent)
3、onCreate()用于启动Service
public void onCreate() {
super.onCreate();
System.out.println("Service onCreate.");
serviceRunning = true;
new Thread(){
@Override
public void run() {
super.run();
while (serviceRunning) {
System.out.println("Service is running...");
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
4、onDestroy()用于停止Service
public void onDestroy() {
super.onDestroy();
System.out.println("Service onDestory.");
serviceRunning = false;
}
5、onStartCommand在Service中传数据
(1)创建editText用于输入数据
public void onClick(View v) {
switch (v.getId()){
case R.id.btnStartService:
intent.putExtra("data",editText.getText().toString());
startService(intent);
break;
case R.id.btnStoptService:
stopService(intent);
break;
case R.id.btnBindtService:
bindService(intent, this, Context.BIND_AUTO_CREATE);
break;
case R.id.btnUnbindtService:
unbindService(this);
break;
}
}
(2)通过intent传递数据
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("Service onCommand.");
data = intent.getStringExtra("data");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
super.onCreate();
System.out.println("Service onCreate.");
serviceRunning = true;
new Thread(){
@Override
public void run() {
super.run();
while (serviceRunning) {
System.out.println(data);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("Service onDestory.");
serviceRunning = false;