您的位置:首页 > 移动开发 > Android开发

Android Programming: Pushing the Limits -- Chapter 6: Services and Background Tasks

2016-06-30 17:13 501 查看
什么时候使用Service服务类型开启服务后台运行服务通信附加资源

什么时候使用Service:

public class MyActivity extends Activity
implements ServiceConnection, MyLocalService.Callback {
private MyLocalService mService;

/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}

@Override
protected void onResume() {
super.onResume();
Intent bindIntent = new Intent(this, MyLocalService.class);
bindService(bindIntent, this, BIND_AUTO_CREATE);
}

@Override
protected void onPause() {
super.onPause();
if (mService != null) {
mService.setCallback(null); // Important to avoid memory leaks
unbindService(this);
}
}

public void onTriggerLongRunningOperation(View view) {
if(mService != null) {
mService.performLongRunningOperation(new MyComplexDataObject());
}
}

@Override
public void onOperationProgress(int progress) {
// TODO Update user interface with progress..
}

@Override
public void onOperationCompleted(MyComplexResult complexResult) {
// TODO Show result to user...
}

@Override
public void onServiceConnected(ComponentName componentName,
IBinder iBinder) {
mService = ((MyLocalService.LocalBinder) iBinder).getService();
mService.setCallback(this);

// Once we have a reference to the service, we can update the UI and
// enable buttons that should otherwise be disabled.
findViewById(R.id.trigger_operation_button).setEnabled(true);
}

@Override
public void onServiceDisconnected(ComponentName componentName) {
// Disable the button as we are loosing the reference to the service.
findViewById(R.id.trigger_operation_button).setEnabled(false);
mService = null;
}
}


MyActivity.java

附加资源:

Google’s changes to the Service API at

http://android-developers.blogspot.se/2010/02/service-api-changes-starting-with.html

Dianne Hackborn at

http://android-developers.blogspot.se/2010/04/multitaskingandroid-way.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: