Service的基本信息
Service的基本用法
package com.example.javy.servicedemo1;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
Log.e("server_threadid", Thread.currentThread().getId() + "");
}
}
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" >
</service>
其中的enabled屬性代表該service能否被實例化,exported代表能否被其它應用程序調用。
如果沒有什麼特別的需求可以不指定這兩個屬性。
做完這兩步~一個android service就已經定義出來了。
接下來看看怎樣調用開啓這個service。
我們可以使用intent調用service,我們就在activity裏調用該service:
Intent intent=new Intent(this,MyService.class);
startService(intent);
可以看到跟調用開啓一個新的activity並無二致,不過不同的是在不指定activity啓動模式的情況下調用activity的時候每調用一次就會新建一個activity。而service則不會,service只會存在一個,如果已經存在了service,再調用開啓service也不會新建service了。
當需要停止service的時候可以調用
stopSelf();
或者 stopService()
就可以停止該service。