標籤:service android 後台運行 作業系統 開發 程式
有些程式不需要互動,在後台運行,並可長時間運行,不被作業系統殺死,這就是組件Service
聲明Service,建立class,MyService,擴充自Service
AndroidManifest中配置, 在Application中添加Serivice,選擇MySerivice
實際添加了一行:
<serviceandroid:name="MyService"></service>
添加二個按鈕,啟動Service和停止Service
<Button
android:id="@+id/btnStartService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="啟動Servive"/>
<Button
android:id="@+id/btnStopService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="停止Service" />
4)代碼中添加二按鈕的定義:
private Button btnStartService,btnStopService;
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStartService=(Button) findViewById(R.id.btnStartService);
btnStopService=(Button) findViewById(R.id.btnStopService);
}
5)添加兩按鈕的監聽事件,滑鼠放紅線處,可自動產生:
(1)btnStartService.setOnClickListener(this);
(2)public class MainActivity extendsActionBarActivity implements OnClickListener
(3)@Override
publicvoid onClick(View v) {
//TODO Auto-generated method stub
}
6) 具體onClick內容:
@Override
publicvoid onClick(View v) {
//TODO Auto-generated method stub
switch(v.getId()){
case R.id.btnStartService:
break;
case R.id.btnStopService:
break;
default:
break;
}
7)啟動Service,需要定義Intent,:
private Intent serviceIntent;
並建立執行個體:
serviceIntent=newIntent(this,MyService.class);
8) 在我們的Service重寫二方法,建立和銷毀:
@Override
publicvoid onCreate(){
System.out.println("建立好了");
super.onCreate();
}
@Override
publicvoid onDestroy(){
System.out.println("被銷毀了");
super.onDestroy();
}
9) 當前Activity銷毀,Service還會再運行,通過設定->應用程式->啟動並執行程式或服務,可看到。
本文出自 “藍海戰術” 部落格,請務必保留此出處http://wanxl.blog.51cto.com/2129901/1589490
10天學通Android開發(2-2)-核心組件Service建立