I am studying on how to develop android sdk with gomobile, here is my use case:
The sdk will handle the file download and it will send its realtime received content to andoird, how could this be done?
I tried something like this, return a ReadCloser, then android will read from this stream :
func DownloadFile(url string) (io.ReadCloser, error) {
// download the file
resp, err := http.Get(url)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
err = errors.New(fmt.Sprintf("requesrting url [%s] error [%s]!", url, resp.Status))
return nil, err
}
return resp.Body, nil
}
however from the compiled java class, there isn't even this method, why?
And I tried to return a channel, but it is the same result, not event compiled in target java class.
Is there any better way to do that? does gomobile supports callback (go sdk call this callback registered by android)? I can hardly find any documentation on that callback usage.
After some googling, I found some useful information, here is a good presentation.
https://talks.madriguera.me/2016/gomobile.slide#17
Finnally, I made my code work:
// define call back interface
type Downloader interface {
Forward(content []byte)
}
// callback instance
var downloader Downloader
// save the callback instance
func RegisterCallback(c Downloader) {
downloader = c
}
func Download(url string) error {
// download the file
resp, err := http.Get(url)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
err = errors.New(fmt.Sprintf("requesrting url [%s] error [%s]!", url, resp.Status))
return err
}
defer resp.Body.Close()
buf := make([]byte, 256)
copyBuffer(resp.Body, buf)
return nil
}
func copyBuffer(src io.Reader, buf []byte) (err error) {
for {
nr, er := src.Read(buf)
if nr > 0 {
content := buf[0:nr]
// callback
downloader.Forward(content)
}
if er == io.EOF {
break
}
if er != nil {
err = er
break
}
}
return nil
}
In Android, I just implement forward interface, then it works well:
// remember call registerCallback() first
@Override
public void forward(byte[] bytes) {
System.out.println("--------------");
System.out.println(new String(bytes));
}