❶ JS怎样调用android本地原生方法
在android中调用本地js文件里的方法并得到返回值其方法如下:
Android中内置了WebKit模块,而该模块的java层视图类就是WebView,所有需要使用Web浏览器功能的Android都需要创建该视图类对象显示和处理请求的网络资源。目前WebKit支持Http、Https、Ftp和JavaScript请求。下面是在Android中调用JavaScript方法以及如何在js中调用本地方法。
1、在Assets下放一个简单的html文件jstest.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html40/strict.dtd">
<HTML>
<HEAD>
<meta name="viewport" content="width=device-width, target-densitydpi=device-dpi" />
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
function showMsg(){
alert("hello world!");
}
function showMsgInAndroid(){
myjs.showMsg('hello in android!');
}
</script>
</HEAD>
<BODY>
<span>测试js使用</span>
<button id='btntest' onclick='showMsgInAndroid()'>调用android方法</button>
</BODY>
</HTML>
2、布局文件main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/rl_main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<WebView
android:id="@+id/wv_test"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@+id/btn_showmsg"/>
<Button
android:id="@+id/btn_showmsg"
android:layout_width="200dip"
android:layout_height="40dip"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="调用html中js方法"/>
</RelativeLayout>
3、然后是Activity,MainActivity.java
package com.harold.jstest;
import com.harold.base.JSKit;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Button;
public class MainActivity extends Activity {
private WebView mWebView;
private Button btnShowInfo;
private JSKit js;
private Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//初始化控件
mWebView = (WebView) findViewById(R.id.wv_test);
btnShowInfo = (Button) findViewById(R.id.btn_showmsg);
//实例化js对象
js = new JSKit(this);
//设置参数
mWebView.getSettings().setBuiltInZoomControls(true);
//内容的渲染需要webviewChromClient去实现,设置webviewChromClient基类,解决js中alert不弹出的问题和其他内容渲染问题
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.getSettings().setJavaScriptEnabled(true);
//把js绑定到全局的myjs上,myjs的作用域是全局的,初始化后可随处使用
mWebView.addJavascriptInterface(js, "myjs");
mWebView.loadUrl("file:///android_asset/jstest.html");
btnShowInfo.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mHandler.post(new Runnable() {
@Override
public void run() {
//调用 HTML 中的javaScript 函数
mWebView.loadUrl("javascript:showMsg()");
}
});
}
});
}
}
4、最后是绑定全局js的类JSKit.java
package com.harold.base;
import android.widget.Toast;
import com.harold.jstest.MainActivity;
public class JSKit {
private MainActivity ma;
public JSKit(MainActivity context) {
this.ma = context;
}
public void showMsg(String msg) {
Toast.makeText(ma, msg, Toast.LENGTH_SHORT).show();
}
}
例子比较简单,代码里都加了注释,这里就不多说了,本示例用的本地的html,如果访问网络中的网页,别忘记在AndroidManifest.xml中加权限
<uses-permission android:name="android.permission.INTERNET"/>
❷ android中handler.post();和view.post();有经验的开发者受累解答下~~~
AsyncTask 分前台任务和后台任务, 后台任务是通过线程池实现的, 运行时你可以通过ddms查看
handler 处理方式很单一, 就是个消息处理. 处理线程是调用loop()方法的那条.
就想了这么多了...
❸ 如何在 Android 上用 Post 提交大量的数据
在 Android 上用 Post 提交大量的数据方法:
1.Android中实现
activity_main.xml部分
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/lblPostResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/butPost"
android:layout_centerHorizontal="true"
android:text="提交结果" />
<Button
android:id="@+id/butPost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="25dp"
android:text="提交测试" />
</RelativeLayout>
//import部分
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Date;
import java.text.SimpleDateFormat;
//public class MainActivity extends Activity 部分
private Button m_butPost;
m_butPost=(Button)findViewById(R.id.butPost);
m_butPost.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
butPost_OnClick(v);
}
});
//提交测试
private void butPost_OnClick(View v){
//请求参数键-值对
String strRecSmsMsg="收短信测试";
//提交
RecSmsToPost(strRecSmsMsg);
openToast("提交测试完成");
}
//收到短信 后 提交
private void RecSmsToPost(String strRecSmsMsg){
String strNowDateTime=getNowDateTime("yyyy-MM-dd|HH:mm:ss");//当前时间
//参数
Map<String,String> params = new HashMap<String,String>();
params.put("RECSMSMSG", strRecSmsMsg);
//params.put("name", "李四");
//服务器请求路径
String strUrlPath = "http://192.168.1.9:80/JJKSms/RecSms.php" +"?DateTime=" + strNowDateTime;
String strResult=HttpUtils.submitPostData(strUrlPath,params, "utf-8");
m_lblPostResult.setText(strResult);
//openToast("提交完成");
}
//获取当前时间
private String getNowDateTime(String strFormat){
if(strFormat==""){
strFormat="yyyy-MM-dd HH:mm:ss";
}
Date now = new Date();
SimpleDateFormat df = new SimpleDateFormat(strFormat);//设置日期格式
return df.format(now); // new Date()为获取当前系统时间
}
//弹出消息
private void openToast(String strMsg){
Toast.makeText(this, strMsg, Toast.LENGTH_LONG).show();
}
HttpUtils 类部分
新建 类文件 HttpUtils 其中代码如下:
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.io.InputStream;
import java.util.Map;
import java.io.IOException;
import java.net.URLEncoder;
import java.io.ByteArrayOutputStream;
public class HttpUtils {
/*
* Function : 发送Post请求到服务器
* Param : params请求体内容,encode编码格式
*/
public static String submitPostData(String strUrlPath,Map<String, String> params, String encode) {
byte[] data = getRequestData(params, encode).toString().getBytes();//获得请求体
try {
//String urlPath = "http://192.168.1.9:80/JJKSms/RecSms.php";
URL url = new URL(strUrlPath);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setConnectTimeout(3000); //设置连接超时时间
httpURLConnection.setDoInput(true); //打开输入流,以便从服务器获取数据
httpURLConnection.setDoOutput(true); //打开输出流,以便向服务器提交数据
httpURLConnection.setRequestMethod("POST"); //设置以Post方式提交数据
httpURLConnection.setUseCaches(false); //使用Post方式不能使用缓存
//设置请求体的类型是文本类型
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//设置请求体的长度
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
//获得输出流,向服务器写入数据
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(data);
int response = httpURLConnection.getResponseCode(); //获得服务器的响应码
if(response == HttpURLConnection.HTTP_OK) {
InputStream inptStream = httpURLConnection.getInputStream();
return dealResponseResult(inptStream); //处理服务器的响应结果
}
} catch (IOException e) {
//e.printStackTrace();
return "err: " + e.getMessage().toString();
}
return "-1";
}
/*
* Function : 封装请求体信息
* Param : params请求体内容,encode编码格式
*/
public static StringBuffer getRequestData(Map<String, String> params, String encode) {
StringBuffer stringBuffer = new StringBuffer(); //存储封装好的请求体信息
try {
for(Map.Entry<String, String> entry : params.entrySet()) {
stringBuffer.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(), encode))
.append("&");
}
stringBuffer.deleteCharAt(stringBuffer.length() - 1); //删除最后的一个"&"
} catch (Exception e) {
e.printStackTrace();
}
return stringBuffer;
}
/*
* Function : 处理服务器的响应结果(将输入流转化成字符串)
* Param : inputStream服务器的响应输入流
*/
public static String dealResponseResult(InputStream inputStream) {
String resultData = null; //存储处理结果
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
try {
while((len = inputStream.read(data)) != -1) {
byteArrayOutputStream.write(data, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
resultData = new String(byteArrayOutputStream.toByteArray());
return resultData;
}
}
2.服务器端的准备
在服务器端我采用wamp方式,当然其它方式也可以。 创建RecSms.php 文件 内容如下:
<?php
require_once ('Log/LogHelper.php');
echo "你好" . "post </br>";
foreach($_REQUEST as $k=>$v){
echo $k;echo "--";
echo $v;echo "</br>";
}
WriteLog('你好 RecSms.php ---------');
foreach($_POST as $k=>$v){
WriteLog( $k .'--' .$v);
}
foreach($_GET as $k=>$v){
WriteLog( $k .'--' .$v);
}
?>
将提交的数据写入Log\Log.php文件中。
其中LogHelper.php 为写日志文件,代码文件如下:
<?php
function WriteLog($msg){
$fp = fopen("Log\Log.php", "a");//文件被清空后再写入
if($fp)
{
date_default_timezone_set('asia/chongqing');
$time=date("H:i:s",strtotime("now"));
$flag=fwrite($fp, $time ." ".$msg ." \r\n");
fclose($fp);
}
}
?>
所有代码已写好。
开启 wamp ,在Android中点击 提交测试 则 在Log.php文件写入提交的数据
❹ android webview中的loadUrl方法是get请求还是post
get请求,因为查询api可以看到有个postUrl方法。查看源码可以确定
❺ android 怎么在oncreate中获得view的坐标
这个问题大家肯定遇到过不止一次,其实很简单,解决它也很容易,但是咱们追求的毕竟不是解决它,而是找到几种方法去解决,并且这么解决的原理是什么。
这里列出4种解决方案:
Activity/View#onWindowFocusChanged
这个函数的含义是:view已经初始化完毕了,宽/高已经准备好了,这个时候去获取宽高是可以成功获取的。但是需要注意的是onWindowFocusChanged函数会被调用多次,当Activity的窗口得到焦点和失去焦点时均会被调用一次,如果频繁地进行onResume和onPause,那么onWindowFocusChanged也会被频繁地调用。
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
L.i("onWindowFocusChanged : v_view1.getWidth():" + v_view1.getWidth()
+ " v_view1.getHeight():" + v_view1.getHeight());
}123456
view.post(runnable)
通过post可以将一个runnable投递到消息队列的尾部,然后等待UI线程Looper调用此runnable的时候,view也已经初始化好了。
v_view1.post(new Runnable() {
@Override
public void run() {
L.i("post(Runnable) : v_view1.getWidth():" + v_view1.getWidth()
+ " v_view1.getHeight():" + v_view1.getHeight());
}
});1234567
ViewTreeObserver
使用ViewTreeObserver的众多回调可以完成这个功能,比如使用OnGlobalLayoutListener这个接口,当view树的状态发生改变或者view树内部的view的可见性发生改变时,onGlobalLayout方法将被回调,因此这是获取view的宽高一个很好的时机。需要注意的是,伴随着view树的状态改变等,onGlobalLayout会被调用多次。
v_view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
L.i("ViewTreeObserver : v_view1.getWidth():" + v_view1.getWidth()
+ " v_view1.getHeight():" + v_view1.getHeight());
}
});1234567
再来详细介绍一下ViewTreeObserver这个类,这个类是用来注册当view tree全局状态改变时的回调监听器,这些全局事件包括很多,比如整个view tree视图的布局,视图绘制的开始,点击事件的改变等等。还有千万不要在应用程序中实例化ViewTreeObserver对象,因为该对象仅是由视图提供的。
ViewTreeObserver类提供了几个相关函数用来添加view tree的相关监听器:
public void addOnDrawListener (ViewTreeObserver.OnDrawListener listener)
该函数为api 16版本中添加,作用是注册在该view tree将要绘制时候的回调监听器,注意该函数和相关的remove函数不能在监听器回调的onDraw()中调用。
public void (ViewTreeObserver.OnGlobalFocusChangeListener listener)
该函数用来注册在view tree焦点改变时候的回调监听器。
public void addOnGlobalLayoutListener (ViewTreeObserver.OnGlobalLayoutListener listener)
该函数用来注册在该view tree中view的全局布局属性改变或者可见性改变时候的回调监听器。
public void addOnPreDrawListener (ViewTreeObserver.OnPreDrawListener listener)
该函数用来注册当view tree将要被绘制时候(view 的 onDraw 函数之前)的回调监听器。
public void addOnScrollChangedListener (ViewTreeObserver.OnScrollChangedListener listener)
该函数用来注册当view tree滑动时候的回调监听器,比如用来监听ScrollView的滑动状态。
public void addOnTouchModeChangeListener (ViewTreeObserver.OnTouchModeChangeListener listener)
该函数用来注册当view tree的touch mode改变时的回调监听器,回调函数onTouchModeChanged (boolean isInTouchMode)中的isInTouchMode为该view tree的touch mode状态。
public void addOnWindowAttachListener (ViewTreeObserver.OnWindowAttachListener listener)
api 18添加,该函数用来注册当view tree被附加到一个window上时的回调监听器。
public void (ViewTreeObserver.OnWindowFocusChangeListener listener)
api 18添加,该函数用来注册当window中该view tree焦点改变时候的回调监听器。
而且对应每一个add方法都会有一个remove方法用来删除相应监听器。
view.measure(int widthMeasureSpec, int heightMeasureSpec)
通过手动对view进行measure来得到view的宽/高,这种情况比较复杂,这里要分情况处理,根据view的layoutparams来分:
match_parent
直接放弃,无法measure出具体的宽/高。原因很简单,根据view的measure过程,构造此种MeasureSpec需要知道parentSize,即父容器的剩余空间,而这个时候我们无法知道parentSize的大小,所以理论上不可能测量处view的大小。
wrap_content
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec((1<<30)-1, View.MeasureSpec.AT_MOST);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec((1<<30)-1, View.MeasureSpec.AT_MOST);
v_view1.measure(widthMeasureSpec, heightMeasureSpec);123
注意到(1<<30)-1,我们知道MeasureSpec的前2位为mode,后面30位为size,所以说我们使用最大size值去匹配该最大化模式,让view自己去计算需要的大小。
具体的数值(dp/px)
这种模式下,只需要使用具体数值去measure即可,比如宽/高都是100px:
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY);
v_view1.measure(widthMeasureSpec, heightMeasureSpec);123
源码和结果
demo代码如下
xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/v_view1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"/>
<View
android:id="@+id/v_view2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@mipmap/ic_launcher"/>
</LinearLayout>12345678910111213141516171819
activity:
public class MainActivity extends BaseActivity{
private View v_view1;
private View v_view2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
v_view1 = findViewById(R.id.v_view1);
v_view2 = findViewById(R.id.v_view2);
L.i("normal: v_view1.getWidth():" + v_view1.getWidth()
+ " v_view1.getHeight():" + v_view1.getHeight());
v_view1.post(new Runnable() {
@Override
public void run() {
L.i("post(Runnable) : v_view1.getWidth():" + v_view1.getWidth()
+ " v_view1.getHeight():" + v_view1.getHeight());
}
});
v_view1.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
L.i("ViewTreeObserver : v_view1.getWidth():" + v_view1.getWidth()
+ " v_view1.getHeight():" + v_view1.getHeight());
}
});
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec((1<<30)-1, View.MeasureSpec.AT_MOST);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec((1<<30)-1, View.MeasureSpec.AT_MOST);
v_view1.measure(widthMeasureSpec, heightMeasureSpec);
L.i("measure : v_view1.getMeasuredWidth():" + v_view1.getMeasuredWidth()
+ " v_view1.getMeasuredHeight():" + v_view1.getMeasuredHeight());
v_view2.measure(widthMeasureSpec, heightMeasureSpec);
L.i("measure : v_view2.getMeasuredWidth():" + v_view2.getMeasuredWidth()
+ " v_view2.getMeasuredHeight():" + v_view2.getMeasuredHeight());
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
L.i("onWindowFocusChanged : v_view1.getWidth():" + v_view1.getWidth()
+ " v_view1.getHeight():" + v_view1.getHeight());
}
}
041424344454647484950
log日志:
I/[PID:2659]: [TID:1] MainActivity.onCreate(line:28): normal: v_view1.getWidth():0 v_view1.getHeight():0
I/[PID:2659]: [TID:1] MainActivity.onCreate(line:50): measure : v_view1.getMeasuredWidth():144 v_view1.getMeasuredHeight():144
I/[PID:2659]: [TID:1] MainActivity.onCreate(line:53): measure : v_view2.getMeasuredWidth():16777215 v_view2.getMeasuredHeight():16777215
I/[PID:2659]: [TID:1] 2.onGlobalLayout(line:42): ViewTreeObserver : v_view1.getWidth():144 v_view1.getHeight():144
I/[PID:2659]: [TID:1] 1.run(line:34): post(Runnable) : v_view1.getWidth():144 v_view1.getHeight():144
I/[PID:2659]: [TID:1] MainActivity.onWindowFocusChanged(line:61): onWindowFocusChanged : v_view1.getWidth():144 v_view1.getHeight():144123456
界面:
小的为view_1,大的为view_2,从log日志中就发现有问题了:view_2视图使用measure之后计算出来的宽高是错误的,所以View类的视图使用measure计算出来的结果是不准确的,这点需要特别特别注意。
❻ android webview 有获取到表单提交数据吗
是可以获取到的,可以通过java的对象,将数据传递到java里面,回调取得值。
❼ 请教android直接post请求登录地址成功后,webview还是现实登录界面
两种情况,1是登录没有真的成功,2是登录后跳转有问题
仔细检查代码,调试
❽ android httppost类在哪
虽然在登录系统中使用了Web Service与服务端进行交互。但是在传递大量的数量时,Web Service显得有些笨拙。在本节将介绍移动电子相册中使用的另外一种与数据库交互的方法。直接发送HTTP GET或POST请求。这就要用到HttpGet、HttpPost以及HttpURLConnection这些类。
15.3.1 HttpGet类和HttpPost类
本节将介绍Android SDK集成的Apache HttpClient模块。要注意的是,这里的Apache HttpClient模块是HttpClient 4.0(org.apache.http.*),而不是Jakarta Commons HttpClient 3.x(org.apache.commons.httpclient.*)。
在HttpClient模块中用到了两个重要的类:HttpGet和HttpPost。这两个类分别用来提交HTTP GET和HTTP POST请求。为了测试本节的例子,需要先编写一个Servlet程序,用来接收HTTP GET和HTTP POST请求。读者也可以使用其他服务端的资源来测试本节的例子。
假设192.168.17.81是本机的IP,客户端可以通过如下的URL来访问服务端的资源:
http://192.168.17.81:8080/querybooks/QueryServlet?bookname=开发
在这里bookname是QueryServlet的请求参数,表示图书名,通过该参数来查询图书信息。
现在我们要通过HttpGet和HttpPost类向QueryServlet提交请求信息,并将返回结果显示在TextView组件中。
无论是使用HttpGet,还是使用HttpPost,都必须通过如下3步来访问HTTP资源。
1.创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。
2.使用DefaultHttpClient类的execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象。
3.通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理。