主类:
1.启动Service:
Intent startIntent = new Intent(主类.this, Service类.class);
startService(startIntent);
2.停止Service(发送广播信息给Service):
Intent stopIntent = new Intent();
stopIntent.setAction("Service类");
stopIntent.puExtra("cmd", 0);
sendBroadcast(stopIntent);
3.编写内部类,用于接收Service服务的消息:
private class DataReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
double data = intent.getDoubleExtra("data", 0);
}
}
4.重写onStart和onStop方法,添加注册和取消注册BroadcastReceicver:
protected void onStart()
{
dataReceiver = new DataReceiver();
IntentFilterfilter = new IntentFilter();
filter.addAction("主类");
registerReceiver(dataReceiver, filter); /*Service服务发送消息时也会设置"主类"这个过滤条件,两边的过滤条件一致,发送的消息才能被正确接收 */
super.onStart();
}
protected void onStop()
{
unregisterReceiver(dataReceiver);
super.onStop();
}
Service类:
1.Service子类需要继续Service类
2.创建内部类,用于接收主类发来的消息(用于停止后台Service服务):
private class CommandReceiver extends BroadcastReceiver
{
@Override
public void onReceiver(Context context, Intent intent)
{
/*主类要停止Service服务的时候,会发送一个广播消息给Service服务,值为0 */
int cmd = intent.getIntExtra("cmd", -1);
if(cmd == 0)
{
stopSelf();
}
}
}
3.重写onBind方法(这步没弄懂):
public IBinder onBind(Intent intent)
{
retun null;
}
4.重写onStartCommand方法(应该是2.1之后的SDK才加进去的方法):
public void onStartCommand(Intent intent, int flags, int startId)
{
/*此处注册的cmdReveicer,用于接收主类发送过来的广播消息(用于停止Service服务),主类和Service类的过滤条件(“Service类”)必须相同 */
IntentFilter filter = new IntentFilter();
filter.addAction("Service类");
registerReceiver(cmdReveicer, filter); /*cmdReveicer为CommandReceiver对象,在onCreate的时候创建*/
/*发送广播消息给主类,同样,主类和Service类的过滤条件(“Service类”)必须相同 */
Intent intent = new Intent();
intent.setAction("主类");
intent.putExtra("data", 777); /*发送数字777给主类 */
sendBroadcast(intent);
return super.onStartCommand(ntent, flags, startId);
}
5.重写onDestroy方法,在该方法中取消注册cmdReveicer
6.