Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 AngularJS 透過 REST API 存取 Android 手機相簿

背景

Android 與 iOS 上有很多遠端存取手機的 App,但開發者普遍缺少能遠端讀取手機特性的 API。myMoKit 這個專案就是為了填補這塊空白而生:它把手機上的相簿、串流等能力包裝成 REST API 對外暴露。

基本用法

使用方式很簡單:只要透過 web URL 引用 myMoKit 服務,就能看到所有已暴露的 REST API 清單。在 AngularJS 這端,用 $resource 服務呼叫這些 API 最為方便。

建立 media 資源模組

angular.module('resources.media', ['ngResource'])
  .factory('Media',
    ['$rootScope', '$resource', '$location', '$http',
     function ($rootScope, $resource, $location, $http) {
       var mediaServices = {};

       mediaServices.getAllMedia = function (media) {
         var path = $rootScope.host + '/services/api/media/' + media;
         return $resource(path, {},
           {
             get: { method: 'GET', isArray: false }
           });
       };

       return mediaServices;
     }]);

取得所有圖片與影片

var getAllImages = function () {
  Media.getAllMedia('image').get().$promise.then(
    function success(resp) {
      $scope.allImages = resp;
      $scope.images = $scope.allImages.images;
    },
    function err(httpResponse) {
      $scope.errorMsg = httpResponse.status;
    });
};

var getAllVideos = function () {
  Media.getAllMedia('video').get().$promise.then(
    function success(resp) {
      $scope.allVideos = resp;
      $scope.videos = $scope.allVideos.videos;
    },
    function err(httpResponse) {
      $scope.errorMsg = httpResponse.status;
    });
};

在瀏覽器裡展示相簿

拿到資料後,用 ng-repeat 搭配 ng-src 就能輕鬆渲染整片縮圖牆:

<div class="alert alert-info">
  <h4 class="alert-heading">Usage - <i>Image Gallery</i></h4>
  <ul class="row">
    <li class="col-lg-2 col-md-2 col-sm-3 col-xs-4"
        ng-repeat="image in images">
      <img class="img-responsive" ng-click="showImage($index)"
           ng-src="{{streamImageLink}}?uri={{image.contentUri}}&&id={{image.id}}&kind=1" />
    </li>
  </ul>
</div>

實作上要注意兩點:一是手機端服務與網頁端通常不同源,需要處理跨來源請求(CORS);二是 $resource 的快取與錯誤處理要明確定義,否則 API 失敗時畫面只會一片空白而無從排查。

英文原文:AngularJS App to access Android Phone Gallery

Copyright © Linux教程網 All Rights Reserved