服务是Android四大组件之一,与Activity同样,表明可执行程序。但Service不像Activity有可操做的用户界面,它是一直在后台运行。用通俗易懂点的话来讲:android
若是某个应用要在运行时向用户呈现可操做的信息就应该选择Activity,若是不是就选择Service。app
Service的生命周期以下:ide
Service只会被建立一次,也只会被销毁一次。那么,如何建立本地服务呢?this
实现代码以下:spa
package temp.com.androidserivce; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.SystemClock; import android.support.annotation.Nullable; import android.util.Log; /** * Created by Administrator on 2017/8/18. */ public class Myservice extends Service { @Override public void onCreate() { Log.i("test", "服务被建立"); super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("test", "服务被启动"); new Thread(new myRunnable(startId)).start(); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { Log.i("test", "服务被销毁"); super.onDestroy(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } class myRunnable implements Runnable { int startId; public myRunnable(int startId) { this.startId = startId; } @Override public void run() { for (int i = 0; i < 10; i++) { SystemClock.sleep(1000); Log.i("test", i + ""); } //中止服务 //stopSelf(); stopSelf(startId); //当用无参数的中止服务时,将会销毁第一次所启动的服务; //当用带参数的中止服务时,将会销毁最末次所启动的服务; } } }
要声明服务,就必须在manifests中进行配置线程
<manifest ... > ... <application ... > <service android:name=".Myservice" android:exported="true"/>
...
</application>
</manifest>
android:exported="true" 设置了这个属性就表示别人也能够使用你的服务。
还有一个须要注意的小点,在Myservice中能够看见我启动时用了一个子线程去帮我实现工做,那么我为何没有直接把for循环的那段代码写在onStartCommand方法中呢,
是由于写在onStartCommand中将会报ANR程序无响应的错误。就是当你全部的事情都去交给主线程作时,就会形成主线程内存溢出,它就会炸了。这个时候也能够用IntentService来取代Service。
package temp.com.androidserivce; import android.app.IntentService; import android.content.Intent; import android.os.SystemClock; import android.util.Log; /** * Created by Administrator on 2017/8/18. */ public class MyService2 extends IntentService { public MyService2() { super(""); } public MyService2(String name) { super(name); } @Override protected void onHandleIntent(Intent intent) { for (int i = 0; i <10 ; i++) { SystemClock.sleep(1000); Log.i("test",i+""); } } }
使用这个相对而言会比较简单。IntentService是Service的子类。它使用工做线程逐一处理全部启动请求。code