[ 启动service ][ 停止Service ]
目录
2. 在AndroidManifest.xml文件中注册Service
1.1 定义Service类
@Override
public IBinder onBind(Intent intent)
是继承Service类一定要包含的函数。
1.2 然后我们通过Override三个函数来学期Serivce的启动,如下:
public void onCreate()
public int onStartCommand(Intent intent, int flags, int startId)
public void onDestroy()
public void onCreate()
onCreate() 是在Service第一次启动时会调用的函数。当Service已经在运行时,再次startService()并不会调用onCreate()函数。
public int onStartCommand(Intent intent, int flags, int startId)
onStartCommand() 是每次启动Service都会调用的函数。即使Service已经启动了,再次startService()还是会调用onStartCommand()函数。
public void onDestroy()
onDestroy() 是停止Service时所调用的函数。在activity中调用stopService()停止函数,会调用这个onDestroy()函数。
1.3 Service 类定义定义如下:
public class MyService extends Service {
public static final String TAG = "MyService";
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate() executed");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand() executed");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() executed");
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
2. 在AndroidManifest.xml文件中注册Service
在<application>中嵌套:
<service android:name="package_name.class_name">
</service>
3. 在Activity中启动Service
Intent intent = new Intent(this, ClassName.class);
startService(intent);
第一次启动Service, 会调用onCreate(), onStartCommand()。之后几次启动Service, 只会调用onStartCommand()。并且Service会一直在后台运行。
4. 停止Service
在Activity中停止Service
Intent intent = new Intent(this, ClassName.class);
stopService(intent);
在停止Service后,再启动Service,则又会调用onCreate(),onStartCommand()。
————————————————
原文链接:https://blog.csdn.net/mozart_cai/article/details/25913889