在phonegap中实例化一个新类

时间:2014-05-17 05:33:55

标签: javascript android cordova

我想从原生android发送一个值到JavaScript。我尝试下面,但我得到nullPointerException,我问这个问题,一个人对我说,我不应该用新的实例化一个活动!但我不知道如何解决这个问题,我怎么能声明这个类,我如何从这个类调用loadUrl()或sendJavascriptInterface()(没有主要的calss,我的意思是在新类中使用这个方法)。我写这段代码。我知道宣布一个新的课是错的,但我不知道如何解决这个问题! :(

public class Test extends DroidGap {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
        super.loadUrl("file:///android_asset/www/index.html");
Log.e("run javascript func from native android", "");


LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000,
        0, locationListener);
 }
}

GPSLocationListener:

public class GPSLocationListener implements LocationListener{

@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
    GPScls MyGPS= new GPScls();
    Log.e(""+location.getLatitude(), ""+location.getLongitude());
    MyGPS.GPS(location.getLatitude(),location.getLongitude());

}
}

 @Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub

}

@Override
 public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub

 }

 }

GPScls:

public class GPScls extends DroidGap {
public void GPS(double latitude,double longitude) {
super.loadUrl("javascript:GPS("+latitude+","+longitude+");");
//this.sendJavascript("javascript:GPS("+latitude+","+longitude+")");
}
 }

我搜索了两天但我无法理解:(

请帮助我,我可以写出正确的代码! 谢谢你的建议

1 个答案:

答案 0 :(得分:1)

在html文件中添加参数以获得所需的值。然后在html脚本标记中添加以下函数以从html url获取值。

function getURLParameter(name) 
{
            return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
        }

然后在文档加载中调用getURLParameter以获取值

var longitude=getURLParameter('longitude');
 var latitude=getURLParameter('latitude');

你的班级

public class Test extends DroidGap {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000,
        0, locationListener);


        super.loadUrl("file:///android_asset/www/index.html?longitude="+longitude+"&latitude="+latitude);
Log.e("run javascript func from native android", "");


 }
}