android服务一般用来做一些,后台操作,数据处理。比较常用。
android服务包括前台服务和后台服务.
前台服务一般用来做音乐的后台播放,可以在通知栏显示。
前台服务的创建:
public class ForegroundService extends Service {
@Override
public void onCreate() {
private NotificationManager mNM;
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION, notification);
}
@Override
public void onDestroy() {
super.onDestroy();
stopForeground(true);
}
}
服务的两种启动方式总结:
startService启动服务后和activity就没关系了,启动多次也只会调用一次onCreate(),会调用多次onStart()。
bindService将服务与activity绑定,activity可以调用service中的方法。
代码例子:
public void class Myservice extends Service {
@Override
public void onCreate()
{
super.onCreate();
}
//用于和外界交互
private final IBinder binder = new MyBinder();
public class MyBinder extends Binder
{
MyService getService()
{
return MyService.this;
}
}
@Override
public IBinder onBind(Intent intent)
{
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
}
@Override
public void onDestroy()
{
}
public void 给activity调用的方法(){}
}
在Activity中绑定服务
public void class MyActivity extends Activity{
private Myservice myservice;
private ServiceConnection mServiceConnection = new ServiceConnection()
{
@Override
public void onServiceDisconnected(ComponentName name)
{
}
@Override
public void onServiceConnected(ComponentName name, IBinder service)
{
// bindService成功的时候返回service的引用
MyBinder myBinder = (MyBinder)service;
mMyService = myBinder.getService();
}
}
@Override
public void onCreate()
{
super.onCreate();
//启动服务
Intent intentService = new Intent(MyActivity.this, MyService.class);
intentService.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intentService.setAction("scott");
//bindService用于和service进行交互
MyActivity.this.bindService(intentService, mServiceConnection, BIND_AUTO_CREATE);
//startService用于启动service但是不和其交互
startService(intentService);
}
}
“`