Android Google Map API ver2 ズームレベル

Android

Android Google Map API ver2 ズームレベル サンプル画像あり

メモ的に書いておきます。

ズームレベルは 2.0 から 21.0 まで選択できます。

数値が大きい方が、ズームイン、小さい方がズームアウトです。

https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/CameraUpdateFactory

 private void cameraZoom( LatLng location ) {
    	float zoom = 15.0f; //ズームレベル
        float tilt = 0.0f; // 0.0 - 90.0  //チルトアングル
        float bearing = 0.0f; //向き
        CameraPosition pos = new CameraPosition(location, zoom, tilt, bearing); //CameraUpdate
        CameraUpdate camera = CameraUpdateFactory.newCameraPosition(pos);
        map.moveCamera(camera);
    }

ちなみに、下記がズームレベル15です。
camera_zoom15.png

下記はズームレベル19です。かなりでかいですね。
camera_zoom19.png

Android Geocoder を利用しようとすると java.io.IOException Service not Availableになる

Android

Android Geocoder を利用しようとすると java.io.IOException Service not Availableになる

なんというか、一定の確率で、これ起こりますね。
困ったことですが、端末を再起動しないと、治らないようです。
何かよい手段が今後できるといいんですけどね…。

http://stackoverflow.com/questions/18249094/geocoder-service-not-available

Android GPSの位置情報設定がされているか調べる

Android

Android GPSの位置情報設定がされているか調べる

Androidの設定画面で、GPSがONになっているかを調べる方法です。
LocationManagerを使った方法がよく紹介されていますが、この設定を調べるためだけにLocationManagerを使うのは大げさだ、という場合、そして、何よりLocationManagerはもう古い!ということで、さくっと設定情報を取ってくるサンプルです。

 String location_provider =
  Settings.Secure.getString(context.getContentResolver(),   
  Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

帰り値は

 0,network,gps

というStringです。
何も設定されていない場合は、0です。

Android GCMでメッセージを送る

Android

Android GCMでメッセージを送る

Androidでプッシュ通知でショートメッセージをおくる仕組みは以前はC2DMというものでしたが、2012年6月26日にデプリケイトされGCM(Google Cloud Messaging for Android)というものに変わりました。

まだまだ途中ではありますが、やってみた経過を書いておきます。

まずは、GCMを利用する準備で、GCM sender IDというものを入手します。

下記のページを参考にして取得します。
http://developer.android.com/guide/google/gcm/gs.html

つまづきやすいポイントを書いておくと

https://code.google.com/apis/console/

にアクセスして、gcmをONにすると、プロジェクトが作れ、そのプロジェクトの後につく番号が、sender IDです。

 例)下記でいえば9779407********、***は伏せ字ですが整数です。
 https://code.google.com/apis/console/#project:9779407********

左のメニューのAPI Accessをクリックすると

Key for browser apps (with referers)

とあるところの

 例)*****は伏せ字ですが、アルファベットの羅列です。
 API key:
 AIzaSyBYyErqLDowHFlZ***********************

が、Webアプリケーション側で利用するAPIキーです。

とりあえず、sender IDとAPIキーは必要になります。

では、次にアプリを作りましょう。
下記のチュートリアルを参考にします。
http://developer.android.com/guide/google/gcm/demo.html

アプリを一から作るのは大変なので、Googleさんがサンプルを用意してくれているのをコピペで作ってみます。
AndroidManifest.xmlとか結構作るの気を使いますよね~。
よい見本にもなります。

SDKマネージャーで、

 Extras > Google Cloud Messaging for Android Library

をインストールします。

すると、

 Android SDKのディレクトリ以下に/extras/google/gcm/samples/gcm-demo-client/

にサンプルアプリがありますので、これを使ってみます。

 /src/com/google/android/gcm/demo/app/CommonUtilities.java

を開くと、ここに定数で先ほどのsender IDとサーバー側アプリケーションのURLを入れる場所があります。

 //例)サーバー側アプリケーションのURLを変更
 static final String SERVER_URL = "http://****.php";
 
 //例)Sender IDを変更
 static final String SENDER_ID = "9779407********";

というように変更します。

これを、エミュレーターで実行すると

 From GCM:error(ACCOUNT_MISSING)

となってしまいます。

ふぇぇーとなりますが、これはGoogleのアカウントがこのエミュレーターにアサインされていないからでした。
Googleアカウントがある実機などで試すと、うまくいきます。
下記のような画面になります。

gcm-avd-home-auto-reg.png

GCMに無事登録されたようです!

デバッガなどでregIDという値をコピペしておきます。

regIDは大変長いです。

 例)regIDの例 ***は伏せ字です 実際はもっと長いアルファベットの羅列です
 'APA91bHqwcC6ztIHr2TZcr2Fmp_eWcqS0E****************************'

そして、Webサーバー側のアプリケーションを用意します。
今回は、下記でご紹介のあったPHPのサンプルを流用させて頂きます。有難うございました。
http://d.hatena.ne.jp/azukinohiroki/20120628/1340868610

 <?php
 
 $url = 'https://android.googleapis.com/gcm/send'; 
 
 $registration_id = 'APA91bHqwcC6ztIHr2TZcr2Fmp_eWcqS0E*********************'; //regIDをここに記述します
 $message = 'Hello, GCM!!';
 
 $header = array(
   'Content-Type: application/x-www-form-urlencoded;charset=UTF-8',
   'Authorization: key=AIzaSyBYyErqLDowHFlZ***********************', //API keyはここ
 );
 $post_list = array(
  'registration_id' => $registration_id,
  'collapse_key' => 'update',
  'data.message' => $message,
 );
 $post = http_build_query($post_list, '&');
 
 $ch = curl_init($url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_FAILONERROR, 1);
 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
 curl_setopt($ch, CURLOPT_POST, TRUE);
 curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
 curl_setopt($ch, CURLOPT_TIMEOUT, 5);
 $ret = curl_exec($ch);
 
 var_dump($ret);
 
 ?>

上記をURLから実行すると、IDが帰ってきて、Android端末にもメッセージが届けば成功です!
とりあえずはやったー(^_^)

 string(38) "id=0:13433901****************" 

Android GCM 受信したメッセージを表示

Android

Android GCM 受信したメッセージを表示

Android GCMでメッセージを送るが多くの方に見て頂いているようで、有難うございます。
なので、調子に乗って、GCMでメッセージをサーバーから受信するところも書いておこうと思います。

Android GCMでメッセージを送るとは違い、サーバーサイドはJsonを利用したスクリプトを用意します。
下記の通りです。(http://labs.distriqt.com/post/1273 さんのものを引用させて頂きました。)

 <?php
 
 $url = 'https://android.googleapis.com/gcm/send';
 
 $registrationId = 'APA91bHqwcC6ztIHr2TZcr2Fmp_eWcqS0EHn796Cd8NKWb32tTJLz***'; //registration IDはここ
 $apiKey="AIzaSyBYyErq****"; //API Keyはここ
  
 //送りたいメッセージ
 $message      = "the test message";
 $tickerText   = "ticker text message";
 $contentTitle = "content title";
 $contentText  = "content body";
 
 
 $response = sendNotification( 
                $apiKey, 
                array($registrationId), 
                array('message' => $message, 'tickerText' => $tickerText, 'contentTitle' => $contentTitle, 
                "contentText" => $contentText) );
 
 echo $response;
 
 function sendNotification( $apiKey, $registrationIdsArray, $messageData )
 {   
    $headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey);
    $data = array(
        'data' => $messageData,
        'registration_ids' => $registrationIdsArray
    );
 
    $ch = curl_init();
 
    curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers ); 
    curl_setopt( $ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send" );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) );
 
    $response = curl_exec($ch);
    curl_close($ch);
 
    return $response;
 } 
 ?>

最初はですね、data、でサーバーに送るのはいいんだけど、アプリ側で取得する時に、何かdataの中に決まった名前で入れなくていいの??と思ったんですが、dataの後は、自分で好きなようにデータの名前をつければいいんですね。

アプリ側は、
Android GCMでメッセージを送るでも利用した、Googleさんが用意してくれているデモアプリの com.google.android.gcm.demo.app を使います。

GCMIntentService.javaのonMessageを次のように変更します。

  protected void onMessage(Context context, Intent intent) {
        Log.i(TAG, "Received message");
        String message = getString(R.string.gcm_message);
        displayMessage(context, message);
        // notifies user
        generateNotification(context, message);
        
        //ここから後を追加        
        String tickerText = intent.getStringExtra("tickerText");
        
        Intent message_intent = new Intent(context, MessageReceivedActivity.class);
        message_intent.putExtra("tickerText", tickerText);
        message_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
        startActivity(message_intent);
        
    }

メッセージを表示するアクティビティを用意します。
このあたりは、Android Cloud to Device Messaging (C2DM) – Tutorialを参考にさせて頂きました。

 //MessageReceivedActivity.javaを追加
 package com.google.android.gcm.demo.app;
  
 import android.app.Activity;
 import android.os.Bundle;
 import android.widget.TextView;
 
 public class MessageReceivedActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_result);
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
    	
      String tickerText = extras.getString("tickerText");
      if (tickerText != null && tickerText.length() > 0) {
        TextView view = (TextView) findViewById(R.id.result);
        view.setText(tickerText);
      }
    }
 
    super.onCreate(savedInstanceState);
  }
 
 } 

レイアウトファイルです。

 //activity_result.xmlを追加
 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical" >
 
    <TextView
        android:id="@+id/result"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:text="No info."
        android:textAppearance="?android:attr/textAppearanceLarge" >
    </TextView>
 
 </LinearLayout> 

サーバーサイドのプログラムを実行すると、次の画面に切り替わり、tickerTextが受け取れたことがわかります。

gcm_message_received.png