Android で JavaScript を使ってみる
GPS 情報を取得してみる(書きかけ)
package hoge.hoge.com;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
import android.location.Location;
import android.location.LocationManager;
public class HelloActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locman = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
Location loc = locman.getLastKnownLocation(LOCATION_SERVICE);
double latitude = loc.getLatitude();//緯度
double longitude = loc.getLongitude();//経度
TextView tv = new TextView(this);
tv.setText( "lat: " + latitude + ", long: " + longitude );
setContentView(tv);
}
}
JavaScript を使ってみる
- assets/www/index.html の作成
<html> <head> <script type="text/javascript"> document.write(anroid.gps("<i>", "</i>")); </script> </head> <body> <p> Hello </p> </body> </html>
- src/hoge.hoge.com/JavaScriptObj.javaの作成
package hoge.hoge.com; import android.content.Context; import android.location.Location; import android.location.LocationManager; public class JavaScriptObj { private Context con; public JavaScriptObj(Context con) { this.con = con; } public String gps(String top, String end) { LocationManager locman = (LocationManager)con.getSystemService(Context.LOCATION_SERVICE); Location loc = locman.getLastKnownLocation(Context.LOCATION_SERVICE); double latitude = loc.getLatitude();//緯度 double longitude = loc.getLongitude();//経度 int lat = (int) (loc.getLatitude() * 1000000); int lon = (int) (loc.getLongitude() * 1000000); return top + "緯度:" + lat + ", 経度: " + lon + end; } }
- src/hoge.hoge.com/HelloActivity.javaの編集
package hoge.hoge.com; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.webkit.WebView; import android.widget.TextView; public class HelloActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); WebView wv = new WebView(this); wv.getSettings().setJavaScriptEnabled(true);//JS利用OK setContentView(wv); JavaScriptObj jo = new JavaScriptObj(this); wv.addJavascriptInterface(jo, "android"); wv.loadUrl("file:///android_asset/www/index.html"); } }
- src/hoge.hoge.com/HelloActivity.javaの編集