* 1.Service是一個應用程序組件
* 2.Service沒有圖形化界面
* 3.Service通常用來處理一些耗時比較長的操作
* 4.可以使用Service更新ContentProvider,發送Intent以及啟動系統的通知等等
*
* 1.Service不是一個單獨的進程
* 2.Service不是一個線程
界面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{ @Override public IBinder onBind(Intent intent) { System.out.println("Service onBind"); return null; } @Override public void onCreate() { super.onCreate(); System.out.println("Service onCreate"); } @Override public 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); } @Override public 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; @Override protected 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{ @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(MainActivity.this, FirstService.class); startService(intent); } } class StopServiceListener implements OnClickListener{ @Override public 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
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。