service繼承於service
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
每一個服務都需要在 AndroidManifest.xml 文件中進行註冊才能生效, 這是 Android 四大組件共有的特點。
啓動和停止service
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_service:
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent); // 啓動服務
break;
case R.id.stop_service:
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent); // 停止服務
break;
default: break;
} }
activity和service的綁定
public class MainActivity extends Activity implements OnClickListener {
private Button startService;
private Button stopService;
private Button bindService;
private Button unbindService;
private MyService.DownloadBinder downloadBinder;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) { }
@Override
public void onServiceConnected(ComponentName name, IBinder service) {}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
⋯⋯
bindService = (Button) findViewById(R.id.bind_service);
unbindService = (Button) findViewById(R.id.unbind_service);
bindService.setOnClickListener(this);
unbindService.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) { ⋯⋯
case R.id.bind_service:
Intent bindIntent = new Intent(this, MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE); // 綁定服務
break;
case R.id.unbind_service:
unbindService(connection); // 解綁服務
break;
default: break;
}
}
}
使用前臺服務
public class MyService extends Service {
@Override
public void onCreate() {
super.onCreate();
Notification notification = new Notification(R.drawable.ic_launcher, "Notification comes", System. currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "This is title", "This is content", pendingIntent);
startForeground(1, notification);
}
IntentService
在運行完畢後確實自動停止了。
集開啓線程和自動停止於一身
service和thread的區別
Service只是從邏輯上表示一個用來執行”longer-running”的”後臺”任務或功能的”application component”。
爲什麼強調說”longer running”的”component”?
這裏是和Activity這種活躍週期相對短暫的component對比而言。一旦用戶切換到其他應用,當前Activity就必須pause, stop甚至被destroy,不能在後臺處理其他事務。
需要強調的事,嚴格來說你仍然可以在activity裏創建自己的worker thread或async task之類做後臺的事情,但這樣做沒有任何保障——因爲一旦你所有的activity都被切換到了後臺,系統隨時可能kill掉你的process,你的後臺任務隨時可能悄無聲息的死掉。
通過在manifest裏聲明Service,把需要後臺相對長期運行的邏輯放在Service裏,你便獲得了這樣的保障:只要系統內存不是極端不夠用,你的Service一定不會被kill掉。對系統而言,當看到一個進程裏有Service在運行,這個進程就具有較高的優先級,會在內存不足被殺的行列裏排得比較靠後。