-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
1220 lines (1005 loc) · 34.1 KB
/
Copy pathmain.go
File metadata and controls
1220 lines (1005 loc) · 34.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Command spec2readme reads YAML spec files (produced by aidl2spec) and
// updates a README.md with generated sections: package listing, quick-start
// example, usage examples, generated-code documentation, and examples table.
// It replaces content between matched marker pairs.
//
// Usage:
//
// spec2readme -specs specs/ -output README.md
package main
import (
"bufio"
"flag"
"fmt"
"math"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"github.com/AndroidGoLab/binder/tools/pkg/spec"
)
const (
moduleBase = "github.com/AndroidGoLab/binder"
)
// generatedDirs lists directories containing generated Go code.
var generatedDirs = []string{"android", "com"}
// codebaseStats holds dynamically computed statistics about the generated codebase.
type codebaseStats struct {
goFiles int
packages int
methods int
interfaces int
}
// computeCodebaseStats counts Go files, packages, and proxy methods in the
// generated code directories.
func computeCodebaseStats() (codebaseStats, error) {
var stats codebaseStats
packageDirs := make(map[string]bool)
proxyMethodRe := regexp.MustCompile(`^func \(p \*\w+`)
interfaceRe := regexp.MustCompile(`^type I\w+ interface \{`)
for _, dir := range generatedDirs {
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil // skip inaccessible paths
}
if info.IsDir() {
return nil
}
if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
return nil
}
stats.goFiles++
packageDirs[filepath.Dir(path)] = true
f, err := os.Open(path)
if err != nil {
return nil
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
if proxyMethodRe.MatchString(line) {
stats.methods++
}
if interfaceRe.MatchString(line) {
stats.interfaces++
}
}
return nil
})
if err != nil {
return stats, fmt.Errorf("walking %s: %w", dir, err)
}
}
stats.packages = len(packageDirs)
return stats, nil
}
func main() {
specsDir := flag.String("specs", "specs/", "Directory containing spec YAML files")
outputPath := flag.String("output", "README.md", "Output README path to update")
examplesDir := flag.String("examples", "examples/", "Directory containing example programs")
flag.Parse()
if err := run(*specsDir, *outputPath, *examplesDir); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
func run(
specsDir string,
outputPath string,
examplesDir string,
) error {
fmt.Fprintf(os.Stderr, "Reading specs from %s...\n", specsDir)
specs, err := spec.ReadAllSpecs(specsDir)
if err != nil {
return fmt.Errorf("reading specs: %w", err)
}
fmt.Fprintf(os.Stderr, "Read %d package specs\n", len(specs))
packages := collectPackageInfo(specs)
sort.Slice(packages, func(i, j int) bool {
return packages[i].importPath < packages[j].importPath
})
examples, err := discoverExamples(examplesDir)
if err != nil {
return fmt.Errorf("discovering examples: %w", err)
}
fmt.Fprintf(os.Stderr, "Found %d examples\n", len(examples))
readme, err := os.ReadFile(outputPath)
if err != nil {
return fmt.Errorf("reading %s: %w", outputPath, err)
}
content := string(readme)
sections := []struct {
name string
content string
}{
{"PACKAGES", renderPackageTable(packages)},
{"QUICK_START", renderQuickStart()},
{"USAGE_EXAMPLES", renderUsageExamples()},
{"GENERATED_CODE", renderGeneratedCode()},
{"EXAMPLES_TABLE", renderExamplesTable(examples)},
{"BINDERCLI_POWER", renderBindercliPower()},
{"BINDER_MCP", renderBinderMCP()},
{"AGENT_CONFIGS", renderAgentConfigs()},
{"INTEROPERABILITY", renderInteroperability()},
}
for _, s := range sections {
beginMarker := fmt.Sprintf("<!-- BEGIN GENERATED %s -->", s.name)
endMarker := fmt.Sprintf("<!-- END GENERATED %s -->", s.name)
content, err = replaceBetweenMarkers(content, beginMarker, endMarker, s.content)
if err != nil {
return fmt.Errorf("section %s: %w", s.name, err)
}
}
// Update inline example count in directory tree.
content = updateExampleCount(content, len(examples))
// Compute and update inline codebase stats.
stats, err := computeCodebaseStats()
if err != nil {
return fmt.Errorf("computing codebase stats: %w", err)
}
fmt.Fprintf(os.Stderr, "Codebase stats: %d Go files, %d packages, %d methods, %d interfaces\n",
stats.goFiles, stats.packages, stats.methods, stats.interfaces)
content = updateInlineStats(content, stats, packages)
return os.WriteFile(outputPath, []byte(content), 0o644)
}
// exampleInfo describes a runnable example in the examples/ directory.
type exampleInfo struct {
name string
desc string
}
// discoverExamples scans the examples directory for subdirectories
// containing main.go files and extracts the first line of the doc comment.
func discoverExamples(dir string) ([]exampleInfo, error) {
entries, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
descriptions := map[string]string{
"list_services": "Enumerate all binder services, ping each",
"activity_manager": "Process limits, monkey test flag, permission checks",
"battery_health": "Capacity, charge status, current draw",
"device_info": "Device properties, build info",
"display_info": "Display IDs, brightness, night mode",
"audio_status": "Audio device info, volume state",
"power_status": "Power supply state, charging info",
"storage_info": "Storage device stats, mount points",
"package_query": "Package list, installation info",
"softap_manage": "WiFi hotspot enable/disable, config",
"softap_wifi_hal": "WiFi chip info, AP interface state",
"softap_tether_offload": "Tethering offload config, stats",
"camera_connect": "Camera device connection with callback stub",
"gps_location": "Live GPS fix via ILocationListener callback",
"flashlight_torch": "Toggle flashlight/torch via ICameraService",
"list_packages": "List all installed packages via GetAllPackages",
"error_handling": "Graceful error handling: service checks, typed errors, permissions",
"server_service": "Register a Go service and call it back via binder",
}
var examples []exampleInfo
for _, e := range entries {
if !e.IsDir() {
continue
}
mainPath := filepath.Join(dir, e.Name(), "main.go")
if _, err := os.Stat(mainPath); err != nil {
continue
}
desc := descriptions[e.Name()]
if desc == "" {
desc = extractDocComment(mainPath)
}
examples = append(examples, exampleInfo{
name: e.Name(),
desc: desc,
})
}
sort.Slice(examples, func(i, j int) bool {
return examples[i].name < examples[j].name
})
return examples, nil
}
// extractDocComment reads the first line of a Go file's package doc comment.
func extractDocComment(path string) string {
data, err := os.ReadFile(path)
if err != nil {
return ""
}
for _, line := range strings.Split(string(data), "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "//") {
return strings.TrimSpace(strings.TrimPrefix(line, "//"))
}
if line != "" {
break
}
}
return ""
}
func renderQuickStart() string {
return `**Go library** — ` + "`go get github.com/AndroidGoLab/binder`" + ` — live GPS location via binder IPC:
` + "```go" + `
package main
import (
"context"
"fmt"
"math"
"os"
"time"
"github.com/AndroidGoLab/binder/android/location"
androidos "github.com/AndroidGoLab/binder/android/os"
"github.com/AndroidGoLab/binder/binder"
"github.com/AndroidGoLab/binder/binder/versionaware"
"github.com/AndroidGoLab/binder/kernelbinder"
"github.com/AndroidGoLab/binder/servicemanager"
)
// gpsListener receives location callbacks from the LocationManager.
type gpsListener struct{ fixCh chan location.Location }
func (l *gpsListener) OnLocationChanged(_ context.Context, locs []location.Location, _ androidos.IRemoteCallback) error {
for _, loc := range locs { select { case l.fixCh <- loc: default: } }
return nil
}
func (l *gpsListener) OnProviderEnabledChanged(_ context.Context, _ string, _ bool) error { return nil }
func (l *gpsListener) OnFlushComplete(_ context.Context, _ int32) error { return nil }
func main() {
ctx := context.Background()
drv, _ := kernelbinder.Open(ctx, binder.WithMapSize(128*1024))
defer drv.Close(ctx)
transport, _ := versionaware.NewTransport(ctx, drv, 0)
sm := servicemanager.New(transport)
lm, _ := location.GetLocationManager(ctx, sm)
impl := &gpsListener{fixCh: make(chan location.Location, 1)}
listener := location.NewLocationListenerStub(impl)
request := location.LocationRequest{
Provider: location.GpsProvider, IntervalMillis: 1000,
ExpireAtRealtimeMillis: math.MaxInt64, DurationMillis: math.MaxInt64,
}
pkg := binder.DefaultCallerIdentity().PackageName
_ = lm.RegisterLocationListener(ctx, location.GpsProvider, request, listener, pkg, "gps")
defer lm.UnregisterLocationListener(ctx, listener)
select {
case loc := <-impl.fixCh:
fmt.Printf("Lat: %.6f Lon: %.6f Alt: %.1f m Accuracy: %.1f m\n",
loc.LatitudeDegrees, loc.LongitudeDegrees, loc.AltitudeMeters, loc.HorizontalAccuracyMeters)
case <-time.After(30 * time.Second):
fmt.Fprintln(os.Stderr, "timed out")
}
}
` + "```" + `
Full runnable example: [` + "`examples/gps_location/`" + `](examples/gps_location/)
Or query power state:
` + "```go" + `
power, _ := os.GetPowerManager(ctx, sm)
interactive, _ := power.IsInteractive(ctx)
fmt.Printf("Screen on: %v\n", interactive)
` + "```" + `
`
}
func renderUsageExamples() string {
return `### Get GPS Location
` + "```go" + `
import (
"context"
"fmt"
"log"
"github.com/AndroidGoLab/binder/android/location"
"github.com/AndroidGoLab/binder/binder"
"github.com/AndroidGoLab/binder/binder/versionaware"
"github.com/AndroidGoLab/binder/kernelbinder"
"github.com/AndroidGoLab/binder/servicemanager"
)
ctx := context.Background()
driver, err := kernelbinder.Open(ctx, binder.WithMapSize(128*1024))
if err != nil {
log.Fatal(err)
}
defer driver.Close(ctx)
transport, err := versionaware.NewTransport(ctx, driver, 0)
if err != nil {
log.Fatal(err)
}
sm := servicemanager.New(transport)
lm, err := location.GetLocationManager(ctx, sm)
if err != nil {
log.Fatal(err)
}
loc, err := lm.GetLastLocation(ctx, location.FusedProvider, location.LastLocationRequest{}, binder.DefaultCallerIdentity().PackageName)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Lat: %f, Lon: %f, Alt: %f\n",
loc.LatitudeDegrees, loc.LongitudeDegrees, loc.AltitudeMeters)
fmt.Printf("Speed: %f m/s, Bearing: %f°\n",
loc.SpeedMetersPerSecond, loc.BearingDegrees)
` + "```" + `
### Check Power State
` + "```go" + `
import (
"context"
"fmt"
"log"
genOs "github.com/AndroidGoLab/binder/android/os"
"github.com/AndroidGoLab/binder/binder"
"github.com/AndroidGoLab/binder/binder/versionaware"
"github.com/AndroidGoLab/binder/kernelbinder"
"github.com/AndroidGoLab/binder/servicemanager"
)
ctx := context.Background()
driver, err := kernelbinder.Open(ctx, binder.WithMapSize(128*1024))
if err != nil {
log.Fatal(err)
}
defer driver.Close(ctx)
transport, err := versionaware.NewTransport(ctx, driver, 0)
if err != nil {
log.Fatal(err)
}
sm := servicemanager.New(transport)
power, err := genOs.GetPowerManager(ctx, sm)
if err != nil {
log.Fatal(err)
}
interactive, _ := power.IsInteractive(ctx)
fmt.Printf("Screen on: %v\n", interactive)
powerSave, _ := power.IsPowerSaveMode(ctx)
fmt.Printf("Power save: %v\n", powerSave)
` + "```" + `
### List Binder Services
` + "```go" + `
sm := servicemanager.New(transport)
services, err := sm.ListServices(ctx)
if err != nil {
log.Fatal(err)
}
for _, name := range services {
svc, err := sm.CheckService(ctx, name)
if err == nil && svc != nil && svc.IsAlive(ctx) {
fmt.Printf("%-60s alive\n", name)
}
}
` + "```" + `
### Call a System Service (ActivityManager)
` + "```go" + `
import (
"github.com/AndroidGoLab/binder/android/app"
"github.com/AndroidGoLab/binder/servicemanager"
)
svc, err := sm.GetService(ctx, servicemanager.ActivityService)
if err != nil {
log.Fatal(err)
}
am := app.NewActivityManagerProxy(svc)
limit, _ := am.GetProcessLimit(ctx)
fmt.Printf("Process limit: %d\n", limit)
monkey, _ := am.IsUserAMonkey(ctx)
fmt.Printf("Is monkey: %v\n", monkey)
` + "```" + `
### Toggle Flashlight
Requires ` + "`android.permission.CAMERA`" + `; see [` + "`examples/flashlight_torch/`" + `](examples/flashlight_torch/) for the full runnable example with permission handling.
` + "```go" + `
import (
"context"
"github.com/AndroidGoLab/binder/android/hardware"
"github.com/AndroidGoLab/binder/binder"
"github.com/AndroidGoLab/binder/parcel"
"github.com/AndroidGoLab/binder/servicemanager"
)
// torchToken is a minimal TransactionReceiver for SetTorchMode's client binder.
type torchToken struct{}
func (t *torchToken) Descriptor() string { return "torch.client" }
func (t *torchToken) OnTransaction(
_ context.Context,
_ binder.TransactionCode,
_ *parcel.Parcel,
) (*parcel.Parcel, error) {
return parcel.New(), nil
}
` + "```" + `
` + "```go" + `
svc, err := sm.GetService(ctx, servicemanager.MediaCameraService)
if err != nil {
log.Fatal(err)
}
camera := hardware.NewCameraServiceProxy(svc)
// The camera service requires a non-null client binder token.
clientToken := binder.NewStubBinder(&torchToken{})
clientToken.RegisterWithTransport(ctx, transport)
// Turn torch on for camera "0"
if err := camera.SetTorchMode(ctx, "0", true, clientToken); err != nil {
log.Fatal(err)
}
fmt.Println("Torch ON")
// Turn torch off
_ = camera.SetTorchMode(ctx, "0", false, clientToken)
` + "```" + `
### List All Installed Packages
` + "```go" + `
import (
"github.com/AndroidGoLab/binder/android/content/pm"
"github.com/AndroidGoLab/binder/servicemanager"
)
svc, err := sm.GetService(ctx, servicemanager.PackageService)
if err != nil {
log.Fatal(err)
}
pkgMgr := pm.NewPackageManagerProxy(svc)
packages, err := pkgMgr.GetAllPackages(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found %d packages:\n", len(packages))
for _, pkg := range packages {
fmt.Println(" ", pkg)
}
` + "```" + `
### Handle Errors Gracefully
` + "```go" + `
import (
"errors"
aidlerrors "github.com/AndroidGoLab/binder/errors"
"github.com/AndroidGoLab/binder/servicemanager"
)
// Non-blocking service check (returns nil if not found)
svc, err := sm.CheckService(ctx, servicemanager.MediaCameraService)
if err != nil {
log.Fatal(err)
}
if svc == nil {
fmt.Println("Camera service not available")
return
}
// Typed error inspection
_, err = someProxy.SomeMethod(ctx)
var status *aidlerrors.StatusError
if errors.As(err, &status) {
switch status.Exception {
case aidlerrors.ExceptionSecurity:
fmt.Printf("Permission denied: %s\n", status.Message)
case aidlerrors.ExceptionServiceSpecific:
fmt.Printf("Service error %d: %s\n", status.ServiceSpecificCode, status.Message)
default:
fmt.Printf("AIDL error: %v\n", status)
}
}
` + "```" + `
### Query Battery Level
` + "```go" + `
import (
"github.com/AndroidGoLab/binder/android/hardware/health"
"github.com/AndroidGoLab/binder/servicemanager"
)
svc, err := sm.GetService(ctx, servicemanager.ServiceName(health.DescriptorIHealth+"/default"))
if err != nil {
log.Fatal(err)
}
h := health.NewHealthProxy(svc)
capacity, err := h.GetCapacity(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Battery level: %d%%\n", capacity)
info, err := h.GetHealthInfo(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Status: %v, Temperature: %.1f °C\n",
info.BatteryStatus, float64(info.BatteryTemperatureTenthsCelsius)/10)
fmt.Printf("Voltage: %d mV, Current: %d µA\n",
info.BatteryVoltageMillivolts, info.BatteryCurrentMicroamps)
` + "```" + `
### Send a Raw Binder Transaction
` + "```go" + `
import (
"github.com/AndroidGoLab/binder/binder"
"github.com/AndroidGoLab/binder/parcel"
"github.com/AndroidGoLab/binder/servicemanager"
)
svc, err := sm.GetService(ctx, servicemanager.ActivityService)
if err != nil {
log.Fatal(err)
}
// Build the request parcel.
data := parcel.New()
defer data.Recycle()
data.WriteInterfaceToken("android.app.IActivityManager")
data.WriteString16("android.permission.INTERNET")
data.WriteInt32(int32(os.Getpid()))
data.WriteInt32(int32(os.Getuid()))
// Resolve the method's transaction code and send.
code, err := svc.ResolveCode(ctx, "android.app.IActivityManager", "checkPermission")
if err != nil {
log.Fatal(err)
}
reply, err := svc.Transact(ctx, code, 0, data)
if err != nil {
log.Fatal(err)
}
defer reply.Recycle()
// Read the AIDL status header, then the return value.
if err := binder.ReadStatus(reply); err != nil {
log.Fatal(err)
}
result, _ := reply.ReadInt32()
fmt.Printf("checkPermission returned: %d\n", result)
` + "```" + `
### Register a Server-Side Service
` + "```go" + `
import (
"context"
"github.com/AndroidGoLab/binder/binder"
"github.com/AndroidGoLab/binder/parcel"
"github.com/AndroidGoLab/binder/servicemanager"
)
// myService implements binder.TransactionReceiver for a simple ping service.
type myService struct{}
func (s *myService) Descriptor() string { return "com.example.IPingService" }
func (s *myService) OnTransaction(
ctx context.Context,
code binder.TransactionCode,
data *parcel.Parcel,
) (*parcel.Parcel, error) {
reply := parcel.New()
binder.WriteStatus(reply, nil)
reply.WriteString16("pong")
return reply, nil
}
` + "```" + `
` + "```go" + `
// Register with ServiceManager
err := sm.AddService(ctx, servicemanager.ServiceName("my.service"), &myService{}, false, 0)
` + "```" + `
<details>
<summary><strong>Using other services</strong></summary>
The examples above cover specific subsystems, but the library supports **all** Android binder services — over 1,500 interfaces. To work with a service not shown above:
1. **Find the service name.** Run ` + "`bindercli service list`" + ` on the device, or check ` + "`servicemanager/service_names_gen.go`" + ` for well-known constants.
2. **Find the generated proxy.** Browse the ` + "`android/`" + ` and ` + "`com/`" + ` packages on [pkg.go.dev](https://pkg.go.dev/github.com/AndroidGoLab/binder) or use ` + "`grep`" + `:
` + "```bash" + `
# Find the proxy for a known AIDL interface
grep -r 'DescriptorI.*= "android.hardware.vibrator.IVibrator"' android/
` + "```" + `
3. **Connect and call methods:**
` + "```go" + `
svc, err := sm.GetService(ctx, servicemanager.ServiceName(
vibrator.DescriptorIVibrator+"/default"))
if err != nil {
log.Fatal(err)
}
proxy := vibrator.NewVibratorProxy(svc)
caps, err := proxy.GetCapabilities(ctx)
` + "```" + `
4. **For HAL services** (hardware abstraction layers), the service name is the AIDL descriptor plus ` + "`/default`" + `:
` + "```go" + `
svc, err := sm.GetService(ctx, servicemanager.ServiceName(health.DescriptorIHealth+"/default"))
` + "```" + `
5. **For services without a generated proxy**, use raw transactions (see [Send a Raw Binder Transaction](#send-a-raw-binder-transaction) above).
</details>
More examples: [` + "`examples/`" + `](examples/)
`
}
func renderGeneratedCode() string {
return `For an AIDL interface like:
` + "```java" + `
// android/app/IActivityManager.aidl
package android.app;
interface IActivityManager {
int getProcessLimit();
int checkPermission(in String permission, int pid, int uid);
boolean isUserAMonkey();
// ... 200+ more methods
}
` + "```" + `
The compiler generates:
` + "```go" + `
package app
const DescriptorIActivityManager = "android.app.IActivityManager"
const (
TransactionIActivityManagerGetProcessLimit = binder.FirstCallTransaction + 51
TransactionIActivityManagerCheckPermission = binder.FirstCallTransaction + 8
// ...
)
const (
MethodIActivityManagerGetProcessLimit = "getProcessLimit"
MethodIActivityManagerCheckPermission = "checkPermission"
// ...
)
type IActivityManager interface {
GetProcessLimit(ctx context.Context) (int32, error)
CheckPermission(ctx context.Context, permission string, pid int32, uid int32) (int32, error)
IsUserAMonkey(ctx context.Context) (bool, error)
// ...
}
type ActivityManagerProxy struct {
Remote binder.IBinder
}
func NewActivityManagerProxy(remote binder.IBinder) *ActivityManagerProxy {
return &ActivityManagerProxy{Remote: remote}
}
func (p *ActivityManagerProxy) GetProcessLimit(ctx context.Context) (int32, error) {
var _result int32
_data := parcel.New()
defer _data.Recycle()
_data.WriteInterfaceToken(DescriptorIActivityManager)
_code, _err := p.Remote.ResolveCode(ctx, DescriptorIActivityManager, MethodIActivityManagerGetProcessLimit)
if _err != nil {
return _result, fmt.Errorf("resolving %s.%s: %w", DescriptorIActivityManager, MethodIActivityManagerGetProcessLimit, _err)
}
_reply, _err := p.Remote.Transact(ctx, _code, 0, _data)
if _err != nil {
return _result, _err
}
defer _reply.Recycle()
if _err = binder.ReadStatus(_reply); _err != nil {
return _result, _err
}
_result, _err = _reply.ReadInt32()
if _err != nil {
return _result, _err
}
return _result, nil
}
` + "```" + `
`
}
func renderExamplesTable(examples []exampleInfo) string {
var b strings.Builder
b.WriteString("| Example | Queries |\n")
b.WriteString("| ---------------------------------------------------------- | --------------------------------------------------- |\n")
for _, ex := range examples {
fmt.Fprintf(&b, "| [`%s`](examples/%s/) | %s |\n", ex.name, ex.name, ex.desc)
}
return b.String()
}
func renderBindercliPower() string {
return `<summary>Query power and battery state</summary>
` + "```bash" + `
# Check if screen is on
bindercli android.os.IPowerManager is-interactive
# Example output: {"result":true}
# Check power save mode
bindercli android.os.IPowerManager is-power-save-mode
# Example output: {"result":false}
# Check if device is in Doze mode
bindercli android.os.IPowerManager is-device-idle-mode
# Example output: {"result":false}
# Get battery health info
bindercli android.hardware.health.IHealth get-health-info
` + "```" + `
`
}
func renderBinderMCP() string {
return `### Device mode
` + "```bash" + `
# Build and push
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -o build/binder-mcp ./cmd/binder-mcp/
adb push build/binder-mcp /data/local/tmp/
# Use with Claude Code (or any MCP client)
# In your MCP config, add:
# {
# "mcpServers": {
# "android": {
# "command": "adb",
# "args": ["shell", "/data/local/tmp/binder-mcp"]
# }
# }
# }
` + "```" + `
### Remote mode (runs on host)
` + "```bash" + `
go run ./cmd/binder-mcp/ --mode remote
# Auto-discovers device via ADB, pushes daemon, serves MCP on stdio
` + "```" + `
### Available tools
| Tool | Description |
|---|---|
| ` + "`list_services`" + ` | Enumerate all binder services |
| ` + "`get_service_info`" + ` | Descriptor, handle, liveness for a service |
| ` + "`call_method`" + ` | Invoke raw binder transactions |
| ` + "`get_device_info`" + ` | Power, display, thermal status |
| ` + "`get_location`" + ` | GPS/fused location |
| ` + "`check_permissions`" + ` | SELinux context and service accessibility |
`
}
func renderAgentConfigs() string {
return `### Installation
` + "```bash" + `
# Via go install
go install github.com/AndroidGoLab/binder/cmd/binder-mcp@latest
# Via GitHub releases (pre-built binaries)
# Download from https://github.com/AndroidGoLab/binder/releases
# Via Docker (host mode)
docker run ghcr.io/androidgolab/binder-mcp
` + "```" + `
### Claude Code
` + "```bash" + `
claude mcp add --transport stdio binder-mcp -- binder-mcp --mode remote
` + "```" + `
### Cursor
Add to ` + "`.cursor/mcp.json`" + `:
` + "```json" + `
{
"mcpServers": {
"binder-mcp": {
"command": "binder-mcp",
"args": ["--mode", "remote"]
}
}
}
` + "```" + `
### Windsurf
Add to ` + "`~/.codeium/windsurf/mcp_config.json`" + `:
` + "```json" + `
{
"mcpServers": {
"binder-mcp": {
"command": "binder-mcp",
"args": ["--mode", "remote"]
}
}
}
` + "```" + `
### Cline
Add to Cline MCP settings:
` + "```json" + `
{
"mcpServers": {
"binder-mcp": {
"command": "binder-mcp",
"args": ["--mode", "remote"],
"alwaysAllow": ["list_services", "get_device_info", "take_screenshot"]
}
}
}
` + "```" + `
### On-device mode (via adb)
` + "```bash" + `
# Build for Android
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -o binder-mcp ./cmd/binder-mcp/
adb push binder-mcp /data/local/tmp/
# Configure agent to use adb transport
claude mcp add --transport stdio binder-mcp -- adb shell /data/local/tmp/binder-mcp
` + "```" + `
`
}
func renderInteroperability() string {
return `<details>
<summary><strong>gadb</strong> — Pure Go ADB for CI/CD</summary>
The ` + "`interop/gadb/runner/`" + ` package provides pure-Go ADB device control
without requiring the ` + "`adb`" + ` binary. Discover devices, push binaries,
and run commands programmatically:
` + "```go" + `
dr, _ := runner.NewDeviceRunner("SERIAL")
dr.PushBinary(ctx, "build/mybinary", "/data/local/tmp/mybinary")
result, _ := dr.Run(ctx, "/data/local/tmp/mybinary", 30*time.Second)
fmt.Println(result.Stdout)
` + "```" + `
For remote binder access from a host machine, ` + "`interop/gadb/proxy/`" + `
sets up a forwarded session:
` + "```go" + `
sess, _ := proxy.NewSession(ctx, "SERIAL")
defer sess.Close(ctx)
// Session manages the daemon lifecycle and port forwarding;
// binder calls are routed through the remote transport.
` + "```" + `
</details>
<details>
<summary><strong>gomobile</strong> — Android AAR</summary>
` + "`interop/gomobile/client/`" + ` wraps binder calls in a Java-friendly API
via gomobile. Build the AAR:
` + "```bash" + `
gomobile bind -target android -o binder.aar ./interop/gomobile/client/
` + "```" + `
Available methods: ` + "`GetPowerStatus()`" + `, ` + "`GetDisplayInfo()`" + `,
` + "`GetLastLocation()`" + `, ` + "`GetDeviceInfo()`" + `.
See the example app at [` + "`examples/gomobile/`" + `](examples/gomobile/).
</details>
`
}
// updateExampleCount replaces "N runnable examples" in the directory tree.
func updateExampleCount(content string, count int) string {
re := regexp.MustCompile(`\d+ runnable examples`)
return re.ReplaceAllString(content, fmt.Sprintf("%d runnable examples", count))
}
// roundDown rounds n down to the nearest multiple of unit.
func roundDown(n, unit int) int {
return (n / unit) * unit
}
// formatCount returns a human-readable count like "14,000" or "5,092".
func formatCount(n int) string {
if n < 1000 {
return fmt.Sprintf("%d", n)
}
thousands := n / 1000
remainder := n % 1000
if remainder == 0 {
return fmt.Sprintf("%d,000", thousands)
}
return fmt.Sprintf("%d,%03d", thousands, remainder)
}