Android之Service启动方式

来源:互联网 发布:工程量预算软件 编辑:程序博客网 时间:2024/06/06 07:47

Service启动方式介绍

一种是通过这种方式启动

Intent intent = new Intent();intent.setClass(MainActivity.this, FirstService.class);MainActivity.this.startService(intent);

还有一种是通过这种方式启动

private ServiceConnection conn = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) {// TODO Auto-generated method stub}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {// TODO Auto-generated method stub}};##<span style="white-space:pre"></span>Intent intent = new Intent(SecondActivity.this, BindService.class);bindService(intent, conn, Context.BIND_AUTO_CREATE);

使用bind方式启动service只能启动一次,而通过startService方式启动service可以启动多次,但是只有第一次会调用onCreate()方法。bind方式启动的service会随activity的关闭而关闭或者通过unbindService()关闭,但是通过startService的方式启动的service不会随activity关闭而关闭,需要调用stopService方法获者stopSelf关闭。

注:线程开启了之后还可以与activity绑定,绑定了之后也可以通过startService()启动

Service生命周期介绍

1-1通过startService()启动的service调用生命周期的过程是

onCreate()

onStartCommand()

onStart()

1-2通过stopService()关闭的service调用生命周期的过程是

onDestroy()

2-1通过bind方式启动的service调用生命周期的过程是

onCreate()

onBind()

2-2通过bind方式关闭的service调用生命周期的过程是

onUnbind()

onDestroy()

接下来请看一个例子

MainActivity.class

public class MainActivity extends Activity {private Button start ;private Button stop ;private Button next;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        start = (Button) findViewById(R.id.start);        stop = (Button) findViewById(R.id.stop);        next = (Button) findViewById(R.id.next);        next.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO 跳转到另一个activityIntent intent = new Intent();intent.setClass(MainActivity.this, BindActivity.class);startActivity(intent);}});        start.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO 启动service,可以启动多次,但是只有第一次会调用onCreate方法Intent intent = new Intent();intent.setClass(MainActivity.this, StartService.class);MainActivity.this.startService(intent);}});        stop.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO 关闭serviceIntent intent = new Intent();intent.setClass(MainActivity.this, StartService.class);MainActivity.this.stopService(intent);}});    }}

FirstService.class

public class StartService extends Service {@Overridepublic IBinder onBind(Intent intent) {Log.e("TAG", "onBind");return null;}/** * 第一次启动调用 */@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();Log.e("TAG", "onCreate");}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubLog.e("TAG", "onStartCommand,startId=" + startId);return super.onStartCommand(intent, flags, startId);}@Override@Deprecatedpublic void onStart(Intent intent, int startId) {// TODO Auto-generated method stubsuper.onStart(intent, startId);Log.e("TAG", "onStart");}@Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();Log.e("TAG", "onDestroy");}@Overridepublic void onLowMemory() {// TODO Auto-generated method stubsuper.onLowMemory();Log.e("TAG", "onLowMemory");}@Overridepublic void onTrimMemory(int level) {// TODO Auto-generated method stubsuper.onTrimMemory(level);Log.e("TAG", "onTrimMemory");}@Overridepublic boolean onUnbind(Intent intent) {// TODO Auto-generated method stubLog.e("TAG", "onUnbind");return super.onUnbind(intent);}@Overridepublic void onRebind(Intent intent) {// TODO Auto-generated method stubsuper.onRebind(intent);Log.e("TAG", "onRebind");}/** * 从后台移除会调用这个方法 */@Overridepublic void onTaskRemoved(Intent rootIntent) {// TODO Auto-generated method stubsuper.onTaskRemoved(rootIntent);Log.e("TAG", "onTaskRemoved");}}

BindActivity.class

public class BindActivity extends Activity {private Button bind;private Button unBind;private Button callMethod;private BindService bindService;private ServiceConnection conn = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) {// TODO Auto-generated method stub}/** * 此处的IBinder是service中onBind()方法返回的 */@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {// TODO Auto-generated method stubMyBinder binder = (MyBinder) service;bindService = binder.getService();}};@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.activity_main);bind = (Button) findViewById(R.id.start);unBind = (Button) findViewById(R.id.stop);callMethod = (Button) findViewById(R.id.next);unBind.setText("解绑service");bind.setText("绑定service");callMethod.setText("调用service方法");bind.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {bindService();}});unBind.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {unBind();}});callMethod.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {bindService.serviceMethod();}});}private void bindService() {Intent intent = new Intent();intent.putExtra("haha", "haha");intent.setClass(BindActivity.this, BindService.class);bindService(intent, conn, Context.BIND_AUTO_CREATE);}private void unBind() {unbindService(conn);}@Overrideprotected void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();}}

BindService.class

public class BindService extends Service {/** * 此处的intent是从bindService方法中传过来的 */@Overridepublic IBinder onBind(Intent intent) {Log.e("TAG", "onBind,intent="+intent.getStringExtra("haha"));return myBinder;}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();Log.e("TAG", "onCreate");}public void serviceMethod() {Log.e("TAG", "调用serviceMethod()");}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubLog.e("TAG", "onStartCommand,startId=" + startId);return super.onStartCommand(intent, flags, startId);}@Override@Deprecatedpublic void onStart(Intent intent, int startId) {// TODO Auto-generated method stubsuper.onStart(intent, startId);Log.e("TAG", "onStart");}@Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();Log.e("TAG", "onDestroy");}@Overridepublic void onLowMemory() {// TODO Auto-generated method stubsuper.onLowMemory();Log.e("TAG", "onLowMemory");}@Overridepublic void onTrimMemory(int level) {// TODO Auto-generated method stubsuper.onTrimMemory(level);Log.e("TAG", "onTrimMemory");}@Overridepublic boolean onUnbind(Intent intent) {// TODO Auto-generated method stubLog.e("TAG", "onUnbind");return super.onUnbind(intent);}@Overridepublic void onRebind(Intent intent) {// TODO Auto-generated method stubsuper.onRebind(intent);Log.e("TAG", "onRebind");}@Overridepublic void onTaskRemoved(Intent rootIntent) {// TODO Auto-generated method stubsuper.onTaskRemoved(rootIntent);Log.e("TAG", "onTaskRemoved");}public class MyBinder extends Binder {public BindService getService() {return BindService.this;}}private MyBinder myBinder = new MyBinder();}


activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.example.servicetest.MainActivity" >    <Button        android:id="@+id/start"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="开启service" />    <Button        android:id="@+id/stop"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="关闭service" />        <Button        android:id="@+id/next"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="下一个" />    </LinearLayout>


AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.servicetest"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="15"        android:targetSdkVersion="19" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name=".MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity            android:name=".BindActivity"            android:label="@string/app_name" >        </activity>        <service            android:name=".StartService"            android:label="@string/app_name" >        </service>        <service            android:name=".BindService"            android:label="@string/app_name" >        </service>    </application></manifest>



0 0
原创粉丝点击