Service代码示例

时间:2022-06-30 05:26:46
 package com.homily.training.service;

 import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log; import com.homily.training.test.service.ICallbackResult; /**
* Created by Rubert on 2016/7/6.
*/
public class BindService extends Service{ private final static String TAG = BindService.class.getSimpleName(); private MBinder mMBinder;
private ICallbackResult mICallbackResult;
private boolean unBindTarget = false; @Nullable
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "============onBind==================");
return mMBinder;
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "============onCreate==================");
mMBinder = new MBinder();
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "============onStartCommand==================");
return super.onStartCommand(intent, flags, startId);
} @Override
public void onDestroy() {
unBindTarget = true;
super.onDestroy();
Log.i(TAG, "============onDestroy==================");
} @Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "============onUnbind==================");
unBindTarget = true;//该处代码需要这么写是因为,Service中开启了线程。如果该Service直接onUnbind了,但是线程没有停止,并且如果再次bind该Service时,程序会再次重新实例化一个线程,并之前的线程也会一直运行下去,除非该app销毁。
return super.onUnbind(intent);
} public class MBinder extends Binder {
public void start(){
Log.i(TAG, "============MBinder-start==================");
new Thread(new Runnable() {
@Override
public void run() { while (true) {
if(unBindTarget) {
break;
}
Log.i(TAG, Thread.currentThread().getName() + "============MBinder-start-run==================");
mICallbackResult.OnBackResult(null);
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
} public void bind(ICallbackResult result) {
mICallbackResult = result;
} } }
 package com.homily.training.service;

 import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log; /**
* Created by Rubert on 2016/7/6.
*/
public class StartService extends Service{ private final static String TAG = StartService.class.getSimpleName(); @Nullable
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "============onBind==================");
return null;
} @Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "============onCreate==================");
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "============onStartCommand==================");
return super.onStartCommand(intent, flags, startId);
} @Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "============onDestroy==================");
} @Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "============onUnbind==================");
return super.onUnbind(intent);
}
}
 package com.homily.training.test.service;

 import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button; import com.homily.training.R;
import com.homily.training.service.BindService;
import com.homily.training.service.StartService; /**
* Created by Rubert on 2016/7/6.
* 主要验证startService 启动后再次启动;以及bindService绑定后,解绑再次绑定的情况。
*/
public class ServiceMainAct extends Activity implements View.OnClickListener{ private final static String TAG = ServiceMainAct.class.getSimpleName(); Button startServiceBtn;
Button closeServiceBtn;
Button bindServiceBtn;
Button unbindServiceBtn;
BindService.MBinder mMBinder;
boolean IsBinder = false; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.service_layout);
startServiceBtn = (Button)findViewById(R.id.startService);
closeServiceBtn = (Button)findViewById(R.id.closeService);
bindServiceBtn = (Button)findViewById(R.id.binService);
unbindServiceBtn = (Button)findViewById(R.id.unbinService); startServiceBtn.setOnClickListener(this);
closeServiceBtn.setOnClickListener(this);
bindServiceBtn.setOnClickListener(this);
unbindServiceBtn.setOnClickListener(this);
} ServiceConnection mConnection = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.i(TAG, "=============onServiceConnected==================");
mMBinder = (BindService.MBinder)iBinder;
mMBinder.bind(mICallbackResult);
mMBinder.start();
IsBinder = true;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
Log.i(TAG, "=============onServiceDisconnected==================");
IsBinder = false;
}
}; ICallbackResult mICallbackResult = new ICallbackResult(){
@Override
public void OnBackResult(Object result) {
Log.i(TAG, "=============result==================");
}
}; @Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.startService:
Intent sintent = new Intent(ServiceMainAct.this, StartService.class);
startService(sintent);
break;
case R.id.closeService:
Intent cintent = new Intent(ServiceMainAct.this, StartService.class);
stopService(cintent);
break;
case R.id.binService:
Intent service = new Intent(ServiceMainAct.this, BindService.class);
bindService(service, mConnection, Context.BIND_AUTO_CREATE);
break;
case R.id.unbinService:
if(mConnection != null && IsBinder)
unbindService(mConnection);
break;
} } }
 package com.homily.training.test.service;

 /**
* Created by Rubert on 2016/7/6.
*/
public interface ICallbackResult {
void OnBackResult(Object result);
}
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" > <service android:name="com.homily.training.service.StartService" />
<service android:name="com.homily.training.service.BindService" /> <activity android:name=".test.service.ServiceMainAct">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
> <Button
android:id="@+id/startService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="startService"
/>
<Button
android:id="@+id/closeService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="closeService"
/> <Button
android:id="@+id/binService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="binService"
/>
<Button
android:id="@+id/unbinService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="unbinService"
/> </LinearLayout>
Android开发的过程中,每次调用startService(Intent)的时候,都会调用该Service对象的onStartCommand(Intent,int,int)方法,然后在onStartCommand方法中做一些处理。然后我们注意到这个函数有一个int的返回值,这篇文章就是简单地讲讲int返回值的作用。
从Android官方文档中,我们知道onStartCommand有4种返回值:
START_STICKY:如果service进程被kill掉,保留service的状态为开始状态,但不保留递送的intent对象。随后系统会尝试重新创建service,由于服务状态为开始状态,所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。如果在此期间没有任何启动命令被传递到service,那么参数Intent将为null。
START_NOT_STICKY:“非粘性的”。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统不会自动重启该服务。
START_REDELIVER_INTENT:重传Intent。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入。
START_STICKY_COMPATIBILITY:START_STICKY的兼容版本,但不保证服务被kill后一定能重启。