提交 2c4a4ebb 编写于 作者: R Ruby Kurosawa

Package Delicated

上级 f4b138f8
package yuki.control.extended;
import android.app.Activity;
import java.io.*;
import java.net.*;
import java.util.Scanner;
/*Http Async Client*/
public final class HttpAsyncClient {
/**
* Async Get String
*
* @param Url URL
* @param activity Window
* @param get Response Handler
**/
public static void AsyncGetString(final String Url, final Activity activity, final OnGet get) {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(Url);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
final String result = readInStream(in);
if (get != null && activity != null && get instanceof OnGetString) {
activity.runOnUiThread(
new Runnable() {
@Override
public void run() {
((OnGetString) get).Get(result);
}
}
);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
}
}).start();
}
private static String readInStream(InputStream in) {
Scanner scanner = new Scanner(in).useDelimiter("\\A");
return scanner.hasNext() ? scanner.next() : "";
}
/**
* Async Get File to local path
*
* @param Url File to download
* @param activity Window
* @param savePath local save path
* @param saveFileName local file name
* @param progress Progress Changed Handler
* @param get Download Finished Handler
**/
public static void AsyncGetFile(final String Url, final Activity activity, final String savePath,
final String saveFileName, final OnProgress progress, final OnGet get) {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(Url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
final int length = conn.getContentLength();
InputStream is = conn.getInputStream();
File file = new File(savePath);
if (!file.exists()) {
file.mkdirs();
}
final String apkFile = savePath + "/" + saveFileName;
File ApkFile = new File(apkFile);
FileOutputStream fos = new FileOutputStream(ApkFile);
int count = 0;
final byte[] buf = new byte[1024];
//double progressu = 0;
do {
int numread = is.read(buf);
count += numread;
final int proceed = count;
final double progressu = (double) (((float) count / length) * 100);
if (activity != null && progress != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
progress.Progress(proceed, length, progressu);
}
});
}
if (numread <= 0) {
//mHandler.sendEmptyMessage(DOWN_OVER);
if (activity != null && get != null && get instanceof OnGetFile) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
((OnGetFile) get).Get(apkFile);
}
});
}
break;
}
fos.write(buf, 0, numread);
} while (true);
fos.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
/**
* Async Get File to local path (filename auto-detected)
*
* @param Url File to download
* @param activity Window
* @param savePath local save path
* @param progress Progress Changed Handler
* @param get Download Finished Handler
**/
public static void AsyncGetFile(final String Url, final Activity activity, final String savePath
, final OnProgress progress, final OnGet get) {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(Url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
final int length = conn.getContentLength();
InputStream is = conn.getInputStream();
File file = new File(savePath);
if (!file.exists()) {
file.mkdirs();
}
final String saveFileName = URLDecoder.decode(url.getFile(), "UTF-8");
final String apkFile = savePath + "/" + saveFileName;
File ApkFile = new File(apkFile);
FileOutputStream fos = new FileOutputStream(ApkFile);
int count = 0;
final byte[] buf = new byte[1024];
//double progressu = 0;
do {
int numread = is.read(buf);
count += numread;
final int proceed = count;
final double progressu = (double) (((float) count / length) * 100);
if (activity != null && progress != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
progress.Progress(proceed, length, progressu);
}
});
}
if (numread <= 0) {
//mHandler.sendEmptyMessage(DOWN_OVER);
if (activity != null && get != null && get instanceof OnGetFile) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
((OnGetFile) get).Get(apkFile);
}
});
}
break;
}
fos.write(buf, 0, numread);
} while (true);
fos.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public static void AsyncPostString(final String Url,final Activity activity,final String ContentType,final String rawData,final OnPost post){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(Url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type",ContentType);
urlConnection.setRequestProperty("Connection","Keep-Alive");
urlConnection.setRequestProperty("Charset", "UTF-8");
urlConnection.setUseCaches(false);
OutputStream out=urlConnection.getOutputStream();
out.write(rawData.getBytes("UTF-8"));
out.flush();
out.close();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
final String result = readInStream(in);
if (post != null && activity != null && post instanceof OnPostString) {
activity.runOnUiThread(
new Runnable() {
@Override
public void run() {
((OnPostString) post).Post(result);
}
}
);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
}
}).start();
}
public static void AsyncRESTString(final String Url,final Activity activity,final String RESTMethod,final String ContentType,final String rawData,final OnREST post){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(Url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod(RESTMethod);
urlConnection.setRequestProperty("Content-Type",ContentType);
urlConnection.setRequestProperty("Connection","Keep-Alive");
urlConnection.setRequestProperty("Charset", "UTF-8");
urlConnection.setUseCaches(false);
OutputStream out=urlConnection.getOutputStream();
out.write(rawData.getBytes("UTF-8"));
out.flush();
out.close();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
final String result = readInStream(in);
if (post != null && activity != null && post instanceof OnRESTString) {
activity.runOnUiThread(
new Runnable() {
@Override
public void run() {
((OnRESTString) post).REST(result);
}
}
);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
}
}).start();
}
}
package yuki.control.extended;
/*OnGet Response Handler*/
public interface OnGet {
}
package yuki.control.extended;
/*On Get Bytes Response Handler*/
public interface OnGetBytes extends OnGet {
/**
* Response Method
*
* @param data Response DataBytes
*/
public void Get(byte[] data);
}
package yuki.control.extended;
/**
* On Get File Handler
*/
public interface OnGetFile extends OnGet {
/**
* Response Method
*
* @param fileName FilePath saved
*/
public void Get(String fileName);
}
package yuki.control.extended;
/**
* On Get String Handler
*/
public interface OnGetString extends OnGet {
/**
* Response Method
*
* @param data String Data
*/
public void Get(String data);
}
package yuki.control.extended;
/**
* Created by Akeno on 2016/08/31.
*/
public interface OnPost {
}
package yuki.control.extended;
/**
* Created by Akeno on 2016/08/31.
*/
public interface OnPostString extends OnPost {
public void Post(String data);
}
package yuki.control.extended;
/**
* Progress Changed Handler
*/
public interface OnProgress {
/**
* Changed Handler
*
* @param proceed Download bytes count
* @param total Total bytes count
* @param progress Download Percentage
**/
public void Progress(int proceed, int total, double progress);
}
package yuki.control.extended;
/**
* Created by Akeno on 2017/08/04.
*/
public interface OnREST {
}
package yuki.control.extended;
/**
* Created by Akeno on 2017/08/04.
*/
public interface OnRESTString extends OnREST {
public void REST(String data);
}
package yuki.pm.extended;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import org.json.JSONObject;
import yuki.control.extended.HttpAsyncClient;
import yuki.control.extended.OnGetString;
/**
* Auto Update Class
*/
public final class AutoUpdateManager {
private Context mContext = null;
private Activity mActivity = null;
private Handler mUpdateHandler = null;
public AutoUpdateManager(Context context, Activity activity, Handler updateHandler) {
mContext = context;
mActivity = activity;
mUpdateHandler = updateHandler;
}
/**
* Check Network Info
*
* @param sharepref Config File
* @param key Config Key
*/
public void NetworkEnvironmentCheck(final String sharepref, final String key) {
final SharedPreferences mobilenetwork = mContext.getSharedPreferences(sharepref, Context.MODE_PRIVATE);
ConnectivityManager mConnectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
boolean lte = false;
if (NetworkManager.GetNetworkType(mContext) != NetworkManager.NO_NETWORK) {
if (NetworkManager.GetNetworkType(mContext) == ConnectivityManager.TYPE_MOBILE) {
lte = true;
}
} else {
AlertDialog.Builder b = new AlertDialog.Builder(mActivity);
b.setTitle("网络不可用");
b.setMessage("没有可用的网络连接,程序将会关闭");
b.setPositiveButton("关闭程序", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
b.show();
return;
}
if ((mobilenetwork == null || !mobilenetwork.contains(key) && lte)) {
AlertDialog.Builder b = new AlertDialog.Builder(mActivity);
b.setTitle("移动网络连接");
b.setMessage("使用移动网络连接会产生流量费用,仍然通过移动网络打开程序?");
b.setPositiveButton("允许移动网络连接", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor e = mobilenetwork.edit();
e.putString("lte", "");
e.apply();
}
});
b.setNeutralButton("允许本次连接", null);
b.setNegativeButton("退出程序", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
b.create().show();
}
}
/**
* Check Update Via Update.JSON
*
* @param updateServer Update Server
* @param pidUpdate Package ID Change Handler
* @param pmUpdate Package Update Found Handler
*/
public void UpdateCheck(final String updateServer, final UpdateClickListener pidUpdate,
final UpdateClickListener pmUpdate) {
UpdateCheck(updateServer, "update.json", pidUpdate, pmUpdate);
}
/**
* Check Update Via Network
*
* @param updateServer UpdateServer
* @param updateFile Update Config File
* @param pidUpdate Package ID Change Handler
* @param pmUpdate Package Update Found Handler
*/
public void UpdateCheck(final String updateServer, final String updateFile, final UpdateClickListener pidUpdate,
final UpdateClickListener pmUpdate) {
HttpAsyncClient.AsyncGetString(updateServer + "/" + updateFile, mActivity, new OnGetString() {
@Override
public void Get(String data) {
try {
final UpdateInfo newUpdateInfo = new UpdateInfo(new JSONObject(data));
final UpdateInfo oldUpdateInfo = new UpdateInfo(pm.GetCurrentVersionName(mContext),
pm.GetCurrentVersionCode(mContext), pm.GetCurrentPackageName(mContext));
if (oldUpdateInfo.getPackageName() != newUpdateInfo.getPackageName()) {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("程序包标识符更新");
builder.setMessage("程序包的标识符更新,更新后需手动卸载旧版本。");
builder.setNegativeButton("取消更新", null);
pidUpdate.setInfo(newUpdateInfo);
builder.setPositiveButton("立即更新", pidUpdate);
builder.create().show();
}
});
} else if (oldUpdateInfo.getVersionCode() < newUpdateInfo.getVersionCode()) {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("程序包更新可用");
builder.setMessage("有新的程序包更新可供安装\n" + "新版本: " +
newUpdateInfo.getVersionName() + "(" + newUpdateInfo.getVersionCode() + ")" +
"\n更新时间: " + newUpdateInfo.getUpdateTime() + "\n更新人:\n" + newUpdateInfo.getUpdater()
+ "\n更新内容:\n" + newUpdateInfo.getUpdateInfo());
builder.setNegativeButton("取消更新", null);
pmUpdate.setInfo(newUpdateInfo);
builder.setPositiveButton("立即更新", pmUpdate);
builder.create().show();
}
});
}
} catch (Exception e) {
final String Data = data;
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("更新出错");
builder.setMessage("无法解析更新数据包\n" + Data);
builder.setNegativeButton("关闭", null);
builder.create().show();
}
});
}
}
});
}
}
package yuki.pm.extended;
/**
* Created by Akeno on 2017/01/05.
*/
public class KeyValuePair<K, V> {
public K getKey() {
return Key;
}
public void setKey(K key) {
Key = key;
}
public V getValue() {
return Value;
}
public void setValue(V value) {
Value = value;
}
private K Key;
private V Value;
}
package yuki.pm.extended;
import java.util.Comparator;
/**
* Created by Akeno on 2017/01/05.
*/
public class KeyValuePairComparator<K,V> implements Comparator {
@Override
public int compare(Object lhs, Object rhs) {
return ((KeyValuePair<K,V>)lhs).getKey().toString().compareTo(((KeyValuePair<K,V>)rhs).getKey().toString());
}
}
package yuki.pm.extended;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
/**
* Network Manager
*/
public class NetworkManager {
public static void OpenWifi(Context context){
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
}
public static void CloseWifi(Context context){
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);
}
public static void OpenData(Context context){
context.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
public static void CloseData(Context context){
context.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
public static String getLocalHostIp()
{
try
{
Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces();
// 遍历所用的网络接口
while (en.hasMoreElements())
{
NetworkInterface nif = en.nextElement();// 得到每一个网络接口绑定的所有ip
Enumeration<InetAddress> inet = nif.getInetAddresses();
// 遍历每一个接口绑定的所有ip
while (inet.hasMoreElements())
{
InetAddress ip = inet.nextElement();
if (!ip.isLoopbackAddress())
{
return ip.getHostAddress();
}
}
}
}
catch (SocketException e)
{
e.printStackTrace();
}
return "0.0.0.0";
}
/**
* Get Current Network Type
*
* @param context Context
* @return NetworkType
*/
public static int GetNetworkType(Context context) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
return mNetworkInfo.getType();
} else {
return NO_NETWORK;
}
}
/**
* Get Ping Status
* @param host Host Name
* @param timeout Timeout
* @return Ping Success
* */
public static boolean Ping(String host,int timeout){
try {
return InetAddress.getByName(host).isReachable(timeout);
} catch (IOException e) {
return false;
}
}
/*NO Network*/
public static int NO_NETWORK = 0;
}
package yuki.pm.extended;
import android.content.DialogInterface;
/**
* Created by Sora-chan on 2015/12/14.
*/
public abstract class UpdateClickListener implements DialogInterface.OnClickListener {
private UpdateInfo info;
/**
* Set Update Info
* @param info Update Info
* */
public void setInfo(UpdateInfo info){
this.info=info;
}
/**
* Get Update Info
* @return Update Info
* */
public UpdateInfo getInfo(){
return this.info;
}
@Override
public abstract void onClick(DialogInterface dialog, int which);
}
package yuki.pm.extended;
import org.json.JSONObject;
/**
* Update Information Struct class.
*/
public class UpdateInfo {
private String versionName;
private int versionCode;
private String updateInfo;
private String updater;
private String updateTime;
private String packageName;
private String updateURL;
/**
* Init Update Info via JSON
*
* @param jsonUpdateData Update JSON Data
* @throws Exception Json Parse Error
*/
public UpdateInfo(JSONObject jsonUpdateData) throws Exception {
versionName = jsonUpdateData.getString("versionName");
versionCode = jsonUpdateData.getInt("versionCode");
updateInfo = jsonUpdateData.getString("updateInfo");
updater = jsonUpdateData.getString("updater");
updateTime = jsonUpdateData.getString("updateTime");
packageName = jsonUpdateData.getString("packageName");
updateURL = jsonUpdateData.getString("updateURL");
}
/**
* Init Update Info via Parameters
*
* @param versionName Version Name
* @param versionCode Version Code
* @param packageName Package ID
*/
public UpdateInfo(String versionName, int versionCode, String packageName) {
this.versionCode = versionCode;
this.versionName = versionName;
this.packageName = packageName;
}
/**
* Return Package ID
*
* @return Pakcage ID
*/
public String getPackageName() {
return packageName;
}
/**
* Return Version Name
*
* @return Version Name
*/
public String getVersionName() {
return versionName;
}
/**
* Return Version Code
*
* @return Version Code
*/
public int getVersionCode() {
return versionCode;
}
/**
* Return Update Description
*
* @return Update Description
*/
public String getUpdateInfo() {
return updateInfo;
}
/**
* Return Update Packager
*
* @return Update Packager
*/
public String getUpdater() {
return updater;
}
/**
* Return Update Time
*
* @return Update Time
*/
public String getUpdateTime() {
return updateTime;
}
/**
* Return Update URL
*
* @return Update URL
*/
public String getUpdateURL(){
return updateURL;
}
}
package yuki.pm.extended;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PermissionInfo;
import android.net.Uri;
import android.os.Build;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Package Manager
*/
public final class pm {
/**
* Get Current Package ID
*
* @param context Context
* @return Package ID
*/
public static String GetCurrentPackageName(Context context) {
ApplicationInfo application = context.getApplicationInfo();
return application.packageName;
}
/**
* Get Current Package Version Code
*
* @param context Context
* @return Version Code
*/
public static int GetCurrentVersionCode(Context context) {
PackageManager packageManager = context.getPackageManager();
try {
return packageManager.getPackageInfo(GetCurrentPackageName(context), 0).versionCode;
} catch (Exception e) {
return 0;
}
}
/**
* Get Current Package Version Name
*
* @param context Context
* @return Version Name
*/
public static String GetCurrentVersionName(Context context) {
PackageManager packageManager = context.getPackageManager();
try {
return packageManager.getPackageInfo(GetCurrentPackageName(context), 0).versionName;
} catch (Exception e) {
return "";
}
}
/**
* Get Package Version Code
*
* @param packageName Package ID
* @param context Context
* @return Version Code
*/
public static int GetPackageVersionCode(Context context, String packageName) {
PackageManager packageManager = context.getPackageManager();
try {
return packageManager.getPackageInfo(packageName, 0).versionCode;
} catch (Exception e) {
return 0;
}
}
/**
* Get Package Version Name
*
* @param packageName Package ID
* @param context Context
* @return Version Code
*/
public static String GetPackageVersionName(Context context, String packageName) {
PackageManager packageManager = context.getPackageManager();
try {
return packageManager.getPackageInfo(packageName, 0).versionName;
} catch (Exception e) {
return "";
}
}
/**
* Install A New Package
*
* @param apkFilePath Package Path
* @param context Context
*/
public static void InstallPackage(Context context, String apkFilePath) {
File apkfile = new File(apkFilePath);
if (!apkfile.exists()) {
return;
}
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
context.startActivity(i);
}
/**
* Get SD Card Folder
*
* @param context Context
* @return SD Card Folder
*/
public static String GetExternalDir(Context context) {
return android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
}
/**
* Get Package Data Foler
*
* @param context Context
* @return Package Data Folder
*/
public static String GetDataDir(Context context) {
return android.os.Environment.getDataDirectory().getAbsolutePath();
}
/**
* Check Permissions
* @param context Context
* @param permission Permission
* @return Result
*/
public static int CheckPermission(Context context,String permission){
PackageManager packageManager = context.getPackageManager();
int ret=packageManager.checkPermission(permission,GetCurrentPackageName(context));
return ret;
}
/**
* Get App's Permissions
* @param context Context
* @return Result
*/
public static List<PermissionInfo> GetPermissions(Context context){
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo pack = packageManager.getPackageInfo(GetCurrentPackageName(context),PackageManager.GET_PERMISSIONS);
String[] permissionStrings = pack.requestedPermissions;
ArrayList<PermissionInfo> pis=new ArrayList<PermissionInfo>();
for (String permission:
permissionStrings) {
try {
PermissionInfo pi = packageManager.getPermissionInfo(permission, 0);
pis.add(pi);
}
catch (Exception ex){
//DO NOTHING
}
}
return pis;
} catch (PackageManager.NameNotFoundException e) {
//DO NOTHING
return new ArrayList<PermissionInfo>();
}
}
/**
* Permission Request
* @param activity Activity
* @param permissions permission
* @param requestCode Code
* @return Result
* */
public static boolean RequestPermissions(Activity activity,String[] permissions,int requestCode){
if(Build.VERSION.SDK_INT>=23) {
activity.requestPermissions(permissions, requestCode);
return true;
}
else{
return true;
}
}
}
package yuki.control.extended;
import android.webkit.JavascriptInterface;
/**
* Geo Location Object.
*/
public final class JSGeoObject {
private boolean _result;
private boolean _GPS;
private double _x;
private double _y;
public JSGeoObject(boolean GPS, boolean result, double lat, double lon) {
_GPS = GPS;
_result = result;
_x = lat;
_y = lon;
}
@JavascriptInterface
public double get_x() {
return get_lat();
}
@JavascriptInterface
public double get_y() {
return get_lon();
}
@JavascriptInterface
public boolean is_location_ok() {
return _result;
}
@JavascriptInterface
public boolean is_GPS_ok() {
return _GPS;
}
@JavascriptInterface
public double get_lat() {
return _x;
}
@JavascriptInterface
public double get_lon() {
return _y;
}
}
package yuki.control.extended;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.webkit.JavascriptInterface;
/**
* YUKI GeoLocation JS Bridge
*/
public class YukiJSBridge {
private Context mContext;
public YukiJSBridge(Context mContext) {
this.mContext = mContext;
}
/**
* JSApi Test Method
*
* @return Integer 1234
*/
@JavascriptInterface
public int test() {
return 1234;
}
/**
* JSApi GeoLocation via GPS
*
* @return GeoLocation
*/
@JavascriptInterface
public JSGeoObject geoGPS() {
LocationManager alm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
if (alm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Location loc = getLocation(LocationManager.GPS_PROVIDER);
boolean locok;
locok = updateToNewLocation(loc);
if (locok) {
return new JSGeoObject(true, locok, lat, lon);
} else {
return new JSGeoObject(true, locok, 0, 0);
}
} else {
return new JSGeoObject(false, false, 0, 0);
}
}
/**
* JSApi GeoLocation via Network
*
* @return GepLocation
*/
@JavascriptInterface
public JSGeoObject geoNetwork() {
LocationManager alm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
if (alm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Location loc = getLocation(LocationManager.NETWORK_PROVIDER);
boolean locok;
locok = updateToNewLocation(loc);
if (locok) {
return new JSGeoObject(true, locok, lat, lon);
} else {
return new JSGeoObject(true, locok, 0, 0);
}
} else {
return new JSGeoObject(false, false, 0, 0);
}
}
private double lat, lon;
private boolean updateToNewLocation(Location location) {
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
return true;
} else {
return false;
}
}
private Location getLocation(String provider) {
LocationManager locationManager;
String serviceName = Context.LOCATION_SERVICE;
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
try {
Location location = locationManager.getLastKnownLocation(provider);
return location;
}
catch (SecurityException ex){
//DO NOTHING
return null;
}
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册