標籤:android 應用程式
* 1.Service是一個應用程式組件
* 2.Service沒有圖形化介面
* 3.Service通常用來處理一些耗時比較長的操作
* 4.可以使用Service更新ContentProvider,發送Intent以及啟動系統的通知等等
*
* 1.Service不是一個單獨的進程
* 2.Service不是一個線程
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M02/54/07/wKiom1R1yy7ywXAyAABEHoxSIcs682.jpg" title="QQ20141126204352.png" alt="wKiom1R1yy7ywXAyAABEHoxSIcs682.jpg" />
介面activity_main.xml
<Button android:id="@+id/startButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Start service"/> <Button android:id="@+id/stopButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/startButton" android:text="Stop service"/>
FirstService.java
public class FirstService extends Service{@Overridepublic IBinder onBind(Intent intent) {System.out.println("Service onBind");return null;}@Overridepublic void onCreate() {super.onCreate();System.out.println("Service onCreate");}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {System.out.println("flags-->" + flags);System.out.println("startId-->" + startId);System.out.println("Service onStartCommand");return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {System.out.println("Service onDestroy");super.onDestroy();}}
MainActivity.java
public class MainActivity extends Activity {/** * 1.Service是一個應用程式組件 * 2.Service沒有圖形化介面 * 3.Service通常用來處理一些耗時比較長的操作 * 4.可以使用Service更新ContentProvider,發送Intent以及啟動系統的通知等等 * * 1.Service不是一個單獨的進程 * 2.Service不是一個線程 * * 啟動Context.startService() * 停止Context.stopService() * Activity繼承自Context所以可以直接調用startService()和stopService()方法 */private Button startButton;private Button stopButton;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);startButton = (Button) findViewById(R.id.startButton);stopButton = (Button) findViewById(R.id.stopButton);startButton.setOnClickListener(new StartServiceListener());stopButton.setOnClickListener(new StopServiceListener());}class StartServiceListener implements OnClickListener{@Overridepublic void onClick(View v) {Intent intent = new Intent();intent.setClass(MainActivity.this, FirstService.class);startService(intent);}}class StopServiceListener implements OnClickListener{@Overridepublic void onClick(View v) {Intent intent = new Intent();intent.setClass(MainActivity.this, FirstService.class);stopService(intent);}}}
先點擊"Start service"按鈕,再點擊"Stop service"按鈕,控制台的輸出如下
11-26 12:42:27.697: I/System.out(1347): Service onCreate
11-26 12:42:35.057: I/System.out(1347): flags-->0
11-26 12:42:35.461: I/System.out(1347): startId-->1
11-26 12:42:35.937: I/System.out(1347): Service onStartCommand
11-26 12:43:07.969: I/System.out(1347): Service onDestroy
本文出自 “阿凡達” 部落格,請務必保留此出處http://shamrock.blog.51cto.com/2079212/1582972
Android學習筆記-Service