jav*_*r71 0 android android-intent android-activity
我是 Android 编程的新手 - 所以我对“上下文”和“意图”不是很清楚。
我想知道有没有办法从 Service 类访问Activity?即假设我有 2 个类 - 一个从“活动”扩展,另一个从“服务”扩展,我在我的活动类中创建了一个意图来启动服务。
或者,如何从我的“活动”类访问“服务”类实例 - 因为在这样的工作流中,服务类不是由我的活动代码直接实例化的。
public class MainActivity extends Activity {
.
.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, CommunicationService.class));
.
.
}
public class CommunicationService extends Service implements ..... {
.
.
@Override
public int onStartCommand(final Intent intent, int flags, final int startId) {
super.onStartCommand(intent, flags, startId);
....
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用bindService(Intent intent, ServiceConnection conn, int flags)代替startService来启动服务。并且conn将是一个内部类,就像:
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mMyService = ((CommunicationService.MyBinder) service).getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
Run Code Online (Sandbox Code Playgroud)
mMyService是您的CommunicationService.
在您的CommunicationService,只需覆盖:
public IBinder onBind(Intent intent) {
return new MyBinder();
}
Run Code Online (Sandbox Code Playgroud)
以及您的以下课程CommunicationService:
public class MyBinder extends Binder {
public CommunicationService getService() {
return CommunicationService.this;
}
}
Run Code Online (Sandbox Code Playgroud)
因此,您可以使用mMyService访问活动中的任何公共方法和字段。
此外,您可以使用回调接口访问服务中的活动。
首先写一个接口,如:
public interface OnChangeListener {
public void onChanged(int progress);
}
Run Code Online (Sandbox Code Playgroud)
在您的服务中,请添加一个公共方法:
public void setOnChangeListener(OnChangeListener onChangeListener) {
this.mOnChangeListener = onChangeListener;
}
Run Code Online (Sandbox Code Playgroud)
您可以onChanged在您的服务中的任何地方使用 ,并且只在您的活动中使用该工具:
public void onServiceConnected(ComponentName name, IBinder service) {
mMyService = ((CommunicationService.MyBinder) service).getService();
mMyService.setOnChangeListener(new OnChangeListener() {
@Override
public void onChanged(int progress) {
// anything you want to do, for example update the progressBar
// mProgressBar.setProgress(progress);
}
});
}
Run Code Online (Sandbox Code Playgroud)
ps:bindService会是这样:
this.bindService(intent, conn, Context.BIND_AUTO_CREATE);
不要忘记
protected void onDestroy() {
this.unbindService(conn);
super.onDestroy();
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你。
| 归档时间: |
|
| 查看次数: |
4117 次 |
| 最近记录: |