生活随笔
收集整理的這篇文章主要介紹了
Android学习笔记-Service
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?* 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{@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
轉載于:https://blog.51cto.com/shamrock/1582972
總結
以上是生活随笔為你收集整理的Android学习笔记-Service的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。