Android 使用 aidl 文件创建服务示例
2010-03-04 03:26:00 来源:WEB开发网sendBroadcast(broadcast)方法来发送一个广播消息通知Activity,然后有Activity注册的接收者进行处理;
*/
private Intent broadcast = new Intent(BROADCAST_ACTION);
sendBroadcast(broadcast);
private final IDataTimeService.Stub binder = new IDataTimeService.Stub() {
public String getForecastPage() {
return (getForecastPageImpl());
}
};
synchronized private String getForecastPageImpl() {
Date date=new Date();
return (date.toLocaleString());
}
@Override
public IBinder onBind(Intent intent) {
return (binder);
}
}
3.现在编写一个Activity,来消费这个服务:
Java代码
public class ServicesDemo2 extends Activity {
private IDataTimeService service = null;
private Intent serviceIntent = null;
private WebView browser;
private ServiceConnection svcConn = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
service = IDataTimeService.Stub.asInterface(binder);
browser.postDelayed(new Runnable() {
public void run() {
updateForecast();
}
}, 1000);
}
public void onServiceDisconnected(ComponentName className) {
service = null;
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
browser = (WebView) findViewById(R.id.webkit);
serviceIntent = new Intent(this, DataTimeServiceImpl.class);
//绑定一个服务
bindService(serviceIntent, svcConn, BIND_AUTO_CREATE);
}
@Override
public void onResume() {
super.onResume();
更多精彩
赞助商链接