Service简介:
Service 是 Android 的四大 组件 之一,一般用于没有UI界面,长期执行的后台任务,即使程序退出时,后台任务还在执行。比如:音乐播放。Service的误区:
1.service在UI线程中执行。 2.不可以在service中执行耗时任务,因为service是在UI线程中运行的。 3.如果需要执行后台的耗时任务,必须在Service中开启一个线程来执行。Service的生命周期:
启动和停止Service的两种方式
1.context.startService();context.stopService().
2.context.bindService();context.unbindService().
第一种方式startService方式
package com.org.broadcast;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private final static String action = "com.org.MainActivity";
private TextView result;
private Button startService;
private Button stopService;
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int i = intent.getIntExtra("key", 0);
result.setText(i + "");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
startService = (Button) findViewById(R.id.startService);
startService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent service = new Intent(MainActivity.this, CalculationService.class);
startService(service);
}
});
stopService = (Button) findViewById(R.id.stopService);
stopService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent service = new Intent(MainActivity.this, CalculationService.class);
stopService(service);
}
});
}
@Override
protected void onResume() {
super.onResume();
initFilter();
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver);
}
private void initFilter() {
IntentFilter filter = new IntentFilter();
filter.addAction(action);
registerReceiver(broadcastReceiver, filter);
}
}
package com.org.broadcast;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class CalculationService extends Service {
private final static String TAG = "CalculationService";
private final static String action = "com.org.MainActivity";
private boolean quit = false;
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG, "====onBind=====");
return null;
}
@Override
public boolean onUnbind(Intent intent) {
Log.e(TAG, "====onUnbind=====");
return super.onUnbind(intent);
}
@Override
public void onCreate() {
Log.e(TAG, "====onCreate=====");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "====onStartCommand=====");
startThread();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.e(TAG, "====onDestroy=====");
quit = true;
super.onDestroy();
}
/**
* 开启线程模拟耗时任务
*/
public void startThread() {
new Thread(new Runnable() {
int i = 0;
@Override
public void run() {
while (i < 200 && !quit) {
try {
Thread.sleep(1000);
i++;
Intent intent = new Intent(action);
intent.putExtra("key", i);
sendBroadcast(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
第二种:bindService 方式
package com.org.broadcast;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private final static String action = "com.org.MainActivity";
private TextView result;
private Button startService;
private Button stopService;
private CalculationService calculationService;
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int i = intent.getIntExtra("key", 0);
result.setText(i + "");
}
};
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
calculationService = ((CalculationService.CalulationBinder) service).getService();
calculationService.startThread();
}
@Override
public void onServiceDisconnected(ComponentName name) {
calculationService = null;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
startService = (Button) findViewById(R.id.startService);
startService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent service = new Intent(MainActivity.this, CalculationService.class);
bindService(service, serviceConnection, Context.BIND_AUTO_CREATE);
}
});
stopService = (Button) findViewById(R.id.stopService);
stopService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
unbindService(serviceConnection);
}
});
}
@Override
protected void onResume() {
super.onResume();
initFilter();
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver);
}
private void initFilter() {
IntentFilter filter = new IntentFilter();
filter.addAction(action);
registerReceiver(broadcastReceiver, filter);
}
}
package com.org.broadcast;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class CalculationService extends Service {
private final static String TAG = "CalculationService";
private final static String action = "com.org.MainActivity";
private boolean quit = false;
private IBinder binder = new CalulationBinder();
public class CalulationBinder extends Binder {
public CalculationService getService() {
return CalculationService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG, "====onBind=====");
return binder;
}
@Override
public boolean onUnbind(Intent intent) {
Log.e(TAG, "====onUnbind=====");
return super.onUnbind(intent);
}
@Override
public void onCreate() {
Log.e(TAG, "====onCreate=====");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "====onStartCommand=====");
startThread();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.e(TAG, "====onDestroy=====");
quit = true; super.onDestroy();
} /** * 开启线程模拟耗时任务 */
public void startThread() {
new Thread(new Runnable() {
int i = 0;
@Override
public void run() {
while (i < 200 && !quit) {
try {
Thread.sleep(1000);
i++;
Intent intent = new Intent(action);
intent.putExtra("key", i);
sendBroadcast(intent);
} catch (InterruptedException e) {
e.printStackTrace();
} } }
}).start(); } }
绑定服务,如果退出的时候没有解除绑定 ,也就是没有调用 context.unbindService().的话,会报错误。所以,
一般都在客户端的 onDestory()中调用 context.unbindService(). 所以这种服务不太适合后台长时间的任务。
这种服务绑定和解除绑定是成对出现的。
两种启动方式总结
第一种,非绑定的Service,应用退出时可以不停止服务退出。可以让服务一直在后台运行。
缺点:启动服务即 启动后台任务,不能很好的在客户端随时控制 服务的后台任务执行时间。
第二种,绑定的Service,应用退出时必须解除绑定Service,否则程序报错。
优点:不过绑定的Service可获得 Service 的Binder,可以灵活控制 Service里的各种方法的调用。