How to set proxy in a webview (Android 6.0 Marshmallow) - Android Q&A, Help & Troubleshooting

Hi all,
I know how to set proxy in a webview under Android 4.4 and less, using java reflection.
But anyone knows how to set a webview proxy under Android 6.0 ? Unfortunatly my methods don't work on this Android version ...
Thanks a lot in advance !
[EDIT] Solved, see post #2

Solved by projection :
Code:
private static boolean setProxyKKPlus(WebView webView, String host, int port, String exclusion, String applicationClassName) {
LOG.warn("try to setProxyKKPlus");
Context appContext = webView.getContext().getApplicationContext();
System.setProperty("http.proxyHost", host);
System.setProperty("http.proxyPort", port + "");
System.setProperty("http.nonProxyHosts", exclusion);
System.setProperty("https.proxyHost", host);
System.setProperty("https.proxyPort", port + "");
System.setProperty("https.nonProxyHosts", exclusion);
try {
Class applictionCls = Class.forName(applicationClassName);
Field loadedApkField = applictionCls.getField("mLoadedApk");
loadedApkField.setAccessible(true);
Object loadedApk = loadedApkField.get(appContext);
Class loadedApkCls = Class.forName("android.app.LoadedApk");
Field receiversField = loadedApkCls.getDeclaredField("mReceivers");
receiversField.setAccessible(true);
ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
for (Object receiverMap : receivers.values()) {
for (Object rec : ((ArrayMap) receiverMap).keySet()) {
Class clazz = rec.getClass();
if (clazz.getName().contains("ProxyChangeListener")) {
Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class, Intent.class);
Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Bundle extras = new Bundle();
List<String> exclusionsList = new ArrayList<>(1);
exclusionsList.add(exclusion);
ProxyInfo proxyInfo = ProxyInfo.buildDirectProxy(host, port, exclusionsList);
extras.putParcelable("android.intent.extra.PROXY_INFO", proxyInfo);
intent.putExtras(extras);
onReceiveMethod.invoke(rec, appContext, intent);
}
}
}
} catch (Exception e) {
LOG.warn("setProxyKKPlus - exception : {}", e);
return false;
}
return true;
}

parameters
what is exclusion and applicationClassName parameters? Im trying to setup proxy on Api 21+

Is anyone able to use buildPacProxy method instead of buildDirectProxy method of ProxyInfo to set the proxy of webview?

Related

[Q] can't transform xml+xsl(with exslt) to html

Hi guys, I am developing an app which loads a xml and a xsl and loads the resulting html, displaying it on the screen. It works perfectly when the xsl does not have exslt functions. However, when it does contain exslt functions, it doesn't work.
The code is rather small, so I'm posting it here:
Code:
public class MainActivity extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webview = new WebView(this);
setContentView(webview);
Source xmlSource = new StreamSource(this.getResources().openRawResource(R.raw.xml2));
Source xsltSource = new StreamSource(this.getResources().openRawResource(R.raw.xsl2));
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = null;
ByteArrayOutputStream output = null;
StreamResult result;
try
{
transformer = tFactory.newTransformer(xsltSource);
output = new ByteArrayOutputStream();
result = new StreamResult(output);
transformer.transform(xmlSource, result);
} catch (TransformerException e)
{
e.printStackTrace();
}
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
String html = new Scanner(input,"UTF-8").useDelimiter("\\A").next();
webview.loadData(html, "text/html", "UTF-8");
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I have attached a zip file containing 5 files: xml,xsl, xml2,xsl2, logcat.
I get the errors with xml2 and xsl2.
I'm using the eclipse IDE, ADT bundle thing. In addition, I have tried an equivalent code in netbeans:
Code:
public class JavaApplication4 {
/**
* [user=955119]@param[/user] args the command line arguments
*/
public static void main(String[] args) throws TransformerConfigurationException, TransformerException, FileNotFoundException {
Source xmlSource = new StreamSource("xml2.xml");
Source xsltSource = new StreamSource("xsl2.xsl");
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(xsltSource);
ByteArrayOutputStream output = new ByteArrayOutputStream();
StreamResult result = new StreamResult(output);
transformer.transform(xmlSource, result);
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
String html = new Scanner(input,"UTF-8").useDelimiter("\\A").next();
System.out.println(html);
}
}
which, to my surprise, works for both xml and xsl.
Please help me, I've been trying to make it work for hours...I've tried many stuff, different codes...but it doesn't seem to have anything to do with my code.
Thank you for your time.

[Q] Google Map is Not Working in Android Emulator.

Hi there
I am trying to Run google Map on Android Emulator But Map is Not Working.I mean Google Map is displaying in Fragment But there is Not any Markers that I place in My Code.
This is My activity class
Java:
double mLatitude=0;
double mLongitude=0;
private GoogleMap map;
Spinner mSprPlaceType;
String[] mPlaceType=null;
String[] mPlaceTypeName=null;
[user=5448622]@Suppress[/user]Lint("NewApi")
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_places1);
// Array of place types
mPlaceType = getResources().getStringArray(R.array.place_type);
// Array of place type names
mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
// Creating an array adapter with an array of Place types
// to populate the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
// Getting reference to the Spinner
mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);
// Setting adapter on Spinner to set place types
mSprPlaceType.setAdapter(adapter);
Button btnFind;
// Getting reference to Find Button
btnFind = ( Button ) findViewById(R.id.button1);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}
else
{
map=((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
// Setting click event lister for the find button
btnFind.setOnClickListener(new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
int selectedPosition = mSprPlaceType.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+mLatitude+","+mLongitude);
sb.append("&radius=10000");
sb.append("&types="+type);
sb.append("&sensor=true");
sb.append("&key=AIzaSyCba6q28XzWhcq5wPaB7ek7HWqh3Sq2Q3A");
// Creating a new non-ui thread task to download json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
});
}
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
[user=439709]@override[/user]
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
[user=439709]@override[/user]
protected void onPostExecute(String result){
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
// Invoked by execute() method of this object
[user=439709]@override[/user]
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = placeJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
[user=439709]@override[/user]
protected void onPostExecute(List<HashMap<String,String>> list){
// Clears all the existing markers
map.clear();
for(int i=0;i<list.size();i++){
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(name + " : " + vicinity);
// Placing a marker on the touched position
map.addMarker(markerOptions);
}
}
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.show_places1, menu);
return true;
}
[user=439709]@override[/user]
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
[user=439709]@override[/user]
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
mLatitude=location.getLatitude();
mLongitude=location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(CameraUpdateFactory.zoomTo(12));
}
[user=439709]@override[/user]
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
[user=439709]@override[/user]
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
[user=439709]@override[/user]
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
And This is My Emulator Defination
Phone_Test2
Nexus S(4.0,480*800hdpi)
Google API(x86 System Image)
Intel Atomx86
HVGA
RAM:500MB
VM Heap:16
Internal Storage:200
SD Card:50
Click to expand...
Click to collapse
I have added all Jars and Permisiion in Manifest.Application is Working fine on Android Powerd Mobile Phone But Not on Android Emulator
any guess?
Thanks

Trouble with string encode after decompile APK file

Hello,
I have a trouble with a string text encode after decompile an APK file.
I used APK Tool decompile.
The code was encoded here:
Code:
public class API
extends Activity
{
public static String a = "081b11458016006d513b0290cc7be0b39c28626ea506b9ed291b125114f2a38369a42e77a066a7789e5883ed47113fc3";
public static String b = "081b11458016006d513b0290cc7be0b36f01584bcfccde8bd9e2bd628ca804e7056b175ad6a1fa1bf3cf31d8a28b94e9";
public static String c = "081b11458016006d513b0290cc7be0b36f01584bcfccde8bd9e2bd628ca804e7056b175ad6a1fa1bf3cf31d8a28b94e9";
public static JSONObject d = new JSONObject();
public static String e = "";
private static int h = 0;
private boolean f = false;
private ProgressDialog g;
private JSONObject a(JSONObject paramJSONObject)
{
int i = 0;
Iterator localIterator = paramJSONObject.keys();
int[] arrayOfInt = new int[paramJSONObject.length()];
int j = 0;
JSONObject localJSONObject1;
int m;
if (!localIterator.hasNext())
{
Arrays.sort(arrayOfInt);
localJSONObject1 = new JSONObject();
m = arrayOfInt.length;
}
for (;;)
{
if (i >= m)
{
return localJSONObject1;
int k = j + 1;
arrayOfInt[j] = Integer.parseInt(((String)localIterator.next()).toString());
j = k;
break;
}
String str1 = Integer.toString(arrayOfInt[i]);
try
{
JSONObject localJSONObject2 = (JSONObject)paramJSONObject.get(str1);
if (((paramJSONObject.get(str1) instanceof JSONObject)) && (!a(localJSONObject2.get("package").toString())))
{
String str2 = localJSONObject2.get("package").toString();
if (!getApplicationContext().getSharedPreferences("listpacks", 0).getBoolean(str2, false)) {
if (localJSONObject2.get("type").toString().equals("1"))
{
if (!this.f)
{
this.f = true;
d = localJSONObject2;
}
}
else
{
e = e + localJSONObject2.get("package").toString() + "|";
localJSONObject1.put(str1, localJSONObject2);
}
}
}
}
catch (JSONException localJSONException)
{
localJSONException.printStackTrace();
}
i++;
}
}
I'm looking for many forum but I'm not find answer.
Anybody can help me decode 3 text string a,b,c please?
Updated: Dear, I have been decode text string by step by step replace char - because I'm not coder.
Result string a:
Code:
081b11458016006d513b0290cc7be0b39c28626ea506b9ed291b125114f2a38369a42e77a066a7789e5883ed47113fc3
is
Code:
http_abc.com/defgh_v2/api_in.php?app_name=9apps&api=19
Update new question, maybe easy: Anybody please tell me what is type encode? ( Again, I'm not a coder but I'm a Google Man hihi)

Evnet insert to Calendar using Calendar API dosn't show on the Calendar App

Following the Google documentation I create an app that insert new events to the user's calendar.
In the following code you can see how I did it.
MakeRequastTask.class
Code:
/**
* An asynchronous task that handles the Google Calendar API call.
* Placing the API calls in their own task ensures the UI stays responsive.
*/
private class MakeRequestTask extends AsyncTask<Void, Void, String[][]> {
private com.google.api.services.calendar.Calendar mServiceCalendar = null;
private Exception mLastError = null;
private String[][] tempArray;
private SpreadSheet mSheet;
MakeRequestTask(GoogleAccountCredential credential, SpreadSheet mSheet) {
this.mSheet = mSheet;
tempArray = new String[7][2];
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
mServiceCalendar = new com.google.api.services.calendar.Calendar.Builder(
transport, jsonFactory, credential)
.setApplicationName("Bank Of Israel")
.build();
}
/**
* Background task to call Google Calendar API.
* @param params no parameters needed for this task.
*/
@Override
protected String[][] doInBackground(Void... params) {
try {
setDataInCalendar();
} catch (Exception e) {
mLastError = e;
cancel(true);
return null;
}
return null;
}
//--- Google Calendar ---\\
private void setDataInCalendar() throws IOException {
Vector<Shift> temp = mSheet.getShifts();
for(Shift s: temp) {
Event e = createEvent(s);
String calendarId = userEmailAddress;
e = mServiceCalendar.events().insert(calendarId, e).execute();
Log.d("MyApp", "Event created: " + e.getHtmlLink());
}
}
private Event createEvent(Shift mShift) {
final String TimeOffSet = "-07:00";
Event event = new Event();
event.setSummary(mShift.getShiftName());//type
//set Date, Start & End Times
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
//make a String for the DateTime Object
//format as: "yyyy-MM-ddTHH:mm:ss+UTCOffSet"
String startTimeUTC = sd.format(mShift.getShiftDate()) +"T"+
mShift.getStartTime().toString() + TimeOffSet ;
DateTime startDateTime = new DateTime(startTimeUTC);
EventDateTime start = new EventDateTime()
.setDateTime(startDateTime);
event.setStart(start);
String endTimeUTC;
//if the shift is C or C1 the end of the shift is in the next day
if (mShift.getShiftName().equals("c1")
||
mShift.getShiftName().equals("c")){
endTimeUTC = sd.format(PatternTest.oneDayForeword(mShift.getShiftDate())) +"T"+
mShift.getEndTime().toString()+ TimeOffSet;
}
else{
endTimeUTC = sd.format(mShift.getShiftDate()) +"T"+
mShift.getEndTime().toString() + IsraelTimeOffSet;
}
DateTime endDateTime = new DateTime(endTimeUTC);
EventDateTime end = new EventDateTime()
.setDateTime(endDateTime);
event.setEnd(end);
event.setColorId("10");
return event;
}
//------------------------------------------------------------------------------------\\
@Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialog();
}
@Override
protected void onPostExecute(String[][] strings) {
super.onPostExecute(strings);
hideProgressDialog();
Toast.makeText(SheetActivity.this, "Finish!", Toast.LENGTH_LONG).show();
}
}
@Override
protected void onCancelled() {
hideProgressDialog();
if (mLastError != null) {
if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
showGooglePlayServicesAvailabilityErrorDialog(
((GooglePlayServicesAvailabilityIOException) mLastError)
.getConnectionStatusCode());
} else if (mLastError instanceof UserRecoverableAuthIOException) {
startActivityForResult(
((UserRecoverableAuthIOException) mLastError).getIntent(),
SheetActivity.REQUEST_AUTHORIZATION);
}
else if (mLastError instanceof NoShiftsInFileException){
Toast.makeText(SheetActivity.this, mLastError.getMessage() , Toast.LENGTH_SHORT).show();
}
else if (mLastError instanceof NoUserNameException){
Toast.makeText(SheetActivity.this, mLastError.getMessage() , Toast.LENGTH_LONG).show();
finish();//go back to the SignIn Activity
}
else {
Toast.makeText(SheetActivity.this, "The following error occurred:\n"
+ mLastError.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(SheetActivity.this, "Request cancelled." , Toast.LENGTH_SHORT).show();
}
}
}
My problem is that after my app insert the new events, I can see them in the web Calendar but the Google Calendar App or any other calendar app I use on my smartphone (LG G2) doesn't show the new events (even after refreshing and resyncing), however when I'm inserting a new event using the web page the event sync perfectly with the apps on my phone.
Thank in advenc

runtime error while accessing google api in android emulator

I am trying to access the googleFit API.
It seems pretty straightforward. Get the google sign-in permissions and required authorizations then query for Step count.
My code doesn't seem to work.
and it logs only "Error!!" that's it.
Android gurus, Where am I going wrong??
Code:
fun getAuthorizationAndReadData() {
try {
MainActivity().fitSignIn(FitActionRequestCode.READ_DATA)
} catch () {
Log.i("e", "error!!!!")
}
}
MainActivity.kt
Code:
enum class FitActionRequestCode {
READ_DATA
}
private val fitnessOptions: GoogleSignInOptionsExtension = FitnessOptions.builder()
.addDataType(DataType.TYPE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_READ).build()
fun fitSignIn(requestCode: FitActionRequestCode) {
if (oAuthPermissionsApproved()) {
readHistoryData()
} else {
requestCode.let {
GoogleSignIn.requestPermissions(
this,
requestCode.ordinal,
getGoogleAccount(), fitnessOptions)
}
}
}
private fun getGoogleAccount() = GoogleSignIn.getAccountForExtension(this, fitnessOptions)
private fun oAuthPermissionsApproved() = GoogleSignIn.hasPermissions(getGoogleAccount(), fitnessOptions)
private fun performActionForRequestCode(requestCode: FitActionRequestCode) = when (requestCode) {
FitActionRequestCode.READ_DATA -> readHistoryData()
}
private fun readHistoryData(): Task<DataReadResponse> {
// Begin by creating the query.
val readRequest = queryFitnessData()
// Invoke the History API to fetch the data with the query
return Fitness.getHistoryClient(this, getGoogleAccount())
.readData(readRequest)
.addOnSuccessListener { dataReadResponse ->
printData(dataReadResponse)
Log.i(ContentValues.TAG, "Data read was successful!") }
.addOnFailureListener { e ->
Log.e(ContentValues.TAG, "There was a problem reading the data.", e)
}
}
private fun queryFitnessData(): DataReadRequest {
// [START build_read_data_request]
// Setting a start and end date using a range of 1 week before this moment.
val calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
val now = Date()
calendar.time = now
val endTime = calendar.timeInMillis
calendar.add(Calendar.WEEK_OF_YEAR, -1)
val startTime = calendar.timeInMillis
return DataReadRequest.Builder()
.aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
.bucketByTime(1, TimeUnit.DAYS)
.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
.build()
}

Categories

Resources