Service生命周期方法,如下所示:
- IBinder onBind(Intent intent) :该方法是Service子类必须实现的的方法.该方法返回一个 IBinder 对象,应用程序可通过该对象与Service组件通信.
- 2.onCreate() :当Service 第一次创建的时候立即调用该方法.
- onDestroy():当Service 关闭之前回调该方法.
- onStartCommand(Intent intent, int flags, int startId):每次客户端调用startService(intent)方法启动该Service时都会调用该方法.
- onUnbind(Intent intent) : 当service 上绑定的所有客户端都断开连接时将会回调该方法.
需要在Activity中启动该service
package com.test.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
/**
* service 的生命周期
*/
public class FirstService extends Service {
public FirstService() {
}
*必须实现的方法*
@Override
public IBinder onBind(Intent intent) {
Log.d("FirstService", "创建服务 service is onBind");
return null;
}
@Override //service 被创建时回调该方法
public void onCreate() {
super.onCreate();
Log.d("FirstService", "创建服务 service is onCreate");
}
@Override //service 被启动时回调该方法
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("FirstService", "启动服务 service is onStartCommand");
return START_STICKY; //return super.onStartCommand(intent, flags, startId);
}
@Override //service 关闭之前回调该方法
public void onDestroy() {
super.onDestroy();
Log.d("FirstService", "关闭服务 service is onDestroy");
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
}
Android中系统中运行Service有如下2种方式:
- 通过 Context的 startService(intent) 方法,通过该方法启动service,访问者与Service之间没有关联,即使访问者退出了,service依然运行.
- 通过 Context的 bindService(intent) 方法,通过该方法启动service,访问者与Service 绑定在一起了,访问者一旦退出了,service 也就终止了.
package com.test.service;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
/**
* service 的简单学习.
*/
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnService = (Button) findViewById(R.id.button);
Button btnStop = (Button) findViewById(R.id.button2);
//创建启动 Service的 Intent
final Intent intent = new Intent();
intent.setAction("com.test.FIRST_SERVICE");
intent.setPackage(this.getPackageName()); //兼容Android 5.0
if (btnService != null) {
btnService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//启动服务
startService(intent);
}
});
}
if (btnStop != null) {
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//停止服务
stopService(intent);
}
});
}
}
}
在清单文件配置
<!--配置一个service组件-->
<application>
<service
android:name=".FirstService"
android:enabled="true"
android:exported="true">
<intent-filter>
<!-- 为该Service组件的intent-filter配置action -->
<action android:name="com.test.FIRST_SERVICE"/>
</intent-filter>
</service>
</application>
780

被折叠的 条评论
为什么被折叠?



