Upate hash parameter in Android WebView - java

I want to update the url hash parameter of a Webview. It reloads the url, if the base url changes, but not if the hash does.
import android.webkit.WebView;
public class MyClass {
private WebView myWebView;
public void start() {
getActivity().runOnUiThread(() -> {
this.assistantWebView.loadUrl("https://www.myCoolName.de/index.html");
}
MyClass self = this;
new android.os.Handler(Looper.getMainLooper()).postDelayed(
new Runnable() {
public void run() {
getActivity().runOnUiThread(() -> {
self.myWebView.loadUrl("https://www.myCoolName.de/index.html#myValue");
});
}
}, 8000);
}
}
After 8 seconds the page flickers shortly, but it did not change anything.
How do I update a page with hashtags?

Related

Xamarin Android - Splash Screen Doesn't Work On Resume

I followed this article and pieced together information with other articles to create a splash screen:
https://learn.microsoft.com/en-us/xamarin/android/user-interface/splash-screen
The splash screen works well when I start the app up by tapping on the app's icon. However, if the app is already running and I switch to it, the screen goes white for a few seconds while the app resumes. Why?
Here is my code:
[Activity(Label = "Hardfolio", Icon = "#drawable/icon", Theme = "#style/MyTheme.Splash", MainLauncher = true, NoHistory = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class SplashActivity : FormsAppCompatActivity
{
static readonly string TAG = "Hardfolio: " + typeof(SplashActivity).Name;
public override void OnCreate(Bundle savedInstanceState, PersistableBundle persistentState)
{
base.OnCreate(savedInstanceState, persistentState);
}
// Launches the startup task
protected override void OnResume()
{
base.OnResume();
var startupWork = new Task(AppStartup);
startupWork.Start();
}
// Simulates background work that happens behind the splash screen
async void AppStartup()
{
StartActivity(new Intent(Application.Context, typeof(MainActivity)));
}
}
[Activity(Label = "Hardfolio", Icon = "#drawable/icon", Theme = "#style/MainTheme", MainLauncher = false, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
[IntentFilter(new[] { UsbManager.ActionUsbDeviceAttached })]
[MetaData(UsbManager.ActionUsbDeviceAttached, Resource = "#xml/device_filter")]
public class MainActivity : Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
#region Fields
private AndroidHidDevice _TrezorHidDevice;
private UsbDeviceAttachedReceiver _UsbDeviceAttachedReceiver;
private UsbDeviceDetachedReceiver _UsbDeviceDetachedReceiver;
private object _ReceiverLock = new object();
#endregion
#region Overrides
protected override void OnCreate(Bundle bundle)
{
try
{
_TrezorHidDevice = new AndroidHidDevice(GetSystemService(UsbService) as UsbManager, ApplicationContext, 3000, 64, TrezorManager.TrezorVendorId, TrezorManager.TrezorProductId);
ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
Xamarin.Forms.Forms.Init(this, bundle);
RegisterReceiver();
var application = new App(new CrossPlatformUtilities(new IsolatedStoragePersister(), new AndroidRESTClientFactory()), _TrezorHidDevice, GetPin);
LoadApplication(application);
}
catch (Exception ex)
{
Logger.Log("Android crash", ex, nameof(Wallet.Droid));
Toast.MakeText(ApplicationContext, ex.ToString(), ToastLength.Long).Show();
}
}
private async Task<string> GetPin()
{
var taskCompletionSource = new TaskCompletionSource<string>();
RunOnUiThread(async () =>
{
var pin = await TrezorPinPad.GetPin();
taskCompletionSource.SetResult(pin);
});
return await taskCompletionSource.Task;
}
protected override void OnResume()
{
base.OnResume();
Logger.Log($"Resuming... Setting up Trezor listeners. _TrezorHidDevice is {(_TrezorHidDevice == null ? "null" : "not null")}", null, nameof(Wallet.Droid));
RegisterReceiver();
}
private void RegisterReceiver()
{
try
{
lock (_ReceiverLock)
{
if (_UsbDeviceAttachedReceiver != null)
{
UnregisterReceiver(_UsbDeviceAttachedReceiver);
_UsbDeviceAttachedReceiver.Dispose();
}
_UsbDeviceAttachedReceiver = new UsbDeviceAttachedReceiver(_TrezorHidDevice);
RegisterReceiver(_UsbDeviceAttachedReceiver, new IntentFilter(UsbManager.ActionUsbDeviceAttached));
if (_UsbDeviceDetachedReceiver != null)
{
UnregisterReceiver(_UsbDeviceDetachedReceiver);
_UsbDeviceDetachedReceiver.Dispose();
}
_UsbDeviceDetachedReceiver = new UsbDeviceDetachedReceiver(_TrezorHidDevice);
RegisterReceiver(_UsbDeviceDetachedReceiver, new IntentFilter(UsbManager.ActionUsbDeviceDetached));
}
}
catch (Exception ex)
{
Logger.Log($"Error registering Hid receivers", ex, nameof(Wallet.Droid));
}
}
#endregion
}
If you start your application, from within another application/or using the ClearTask flag/or if your app is performing a cold start (has been closed in the background), and perhaps i other ways as well, you will see a "Preview" screen, which is the background of your current theme (kind of what you are already doing for your SplashScreen, which shows the theme background)...
But if your "#style/MainTheme" has a simple white background, this will be what you might see when reentering your app.
Therefore you can consider using the "SetTheme" method in OnCreate. There is more about this in this link:
https://developer.android.com/topic/performance/vitals/launch-time
Hope it helps.

UnityPlayerActivity global initialization

I'd appreciate if you could advise on my problem.
I'm working on AR app using Vuforia SDK for Unity3D and Android plugins.
I have several ImageTargets and 3D models on my scene.
My class that works with android plugin looks like this:
public class AssetBundleAugmenter : MonoBehaviour, ITrackableEventHandler
{
void Start()
{
StartCoroutine(DownloadAndCache());
mTrackableBehaviour = GetComponent<TrackableBehaviour>();
if (mTrackableBehaviour)
{
mTrackableBehaviour.RegisterTrackableEventHandler(this);
}
init();
}
public void OnTrackableStateChanged(
TrackableBehaviour.Status previousStatus,
TrackableBehaviour.Status newStatus)
{
if (newStatus == TrackableBehaviour.Status.DETECTED ||
newStatus == TrackableBehaviour.Status.TRACKED ||
newStatus == TrackableBehaviour.Status.EXTENDED_TRACKED)
{
if (!mAttached && mBundleInstance)
{
// if bundle has been loaded, let's attach it to this trackable
//...
}
OnTrackingFound();
}
else
{
OnTrakingLost();
}
}
private void OnTrackingFound()
{
if (mTrackableBehaviour is ImageTargetAbstractBehaviour)
{
GetJavaObject().Call("OnMarkerFound");
}
}
void onButtonClicked(int index)
{
//Changing current 3D model material
}
#if UNITY_ANDROID
private AndroidJavaObject javaObj = null;
//LISTENING TO BUTTON CLICK EVENTS FROM ANDROID
private sealed class EventListner : AndroidJavaProxy
{
private AssetBundleAugmenter mReceiver;
public EventListner(AssetBundleAugmenter receiver)
: base("com.mypackage.myapp.ImageTargetTracker$Listner")
{
mReceiver = receiver;
}
public void onButtonClicked(int index) //change color of model
{
mReceiver.onButtonClicked(index);
}
}
private AndroidJavaObject GetJavaObject()
{
if (javaObj == null)
{
javaObj = new AndroidJavaObject("com.mypackage.myapp.ImageTargetTracker");
}
return javaObj;
}
AndroidJavaObject activity;
private void init()
{
// Retrieve current Android Activity from the Unity Player
AndroidJavaClass jclass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
activity = jclass.GetStatic<AndroidJavaObject>("currentActivity");
// Pass reference to the current Activity into the native plugin,
GetJavaObject().Call("setActivity", activity, new EventListner(this));
}
#else
void init() {}
#endif
}
So I attached this script to all of my ImageTargets on the scene, which I know must be wrong, because UnityPlayer gets initialized several times in my init() function.
I tried to attach the script to ARCamera on my scene, and write initialization only there, but I'm not sure how to access currentActivity in scripts that work with ImageTargets. Also, I use listener - the interface in my plugin that listens to button clicks to fire some functionality in unity.
My plugin code:
public class ImageTargetTracker {
public static interface Listner {
public void onButtonClicked(int index);
}
private Listner mListner;
protected Activity mCurrentActivity;
public void setActivity(Activity activity, Listner listner)
{
mCurrentActivity = activity;
mListner = listner;
mCurrentActivity.runOnUiThread(new Runnable() {
public void run() {
LayoutInflater inflater = mCurrentActivity.getLayoutInflater();
Resources resources = mCurrentActivity.getResources();
String pkgName = mCurrentActivity.getPackageName();
int id = resources.getIdentifier("camera_layout", "layout", pkgName);
View view = inflater.inflate(id, null);
mCurrentActivity.addContentView(view, param);
//INITIALIZING UI ELEMENTS HERE (DISPLAYED ON TOP OF CAMERA)
}
public void OnMarkerFound(){
mCurrentActivity.runOnUiThread(new Runnable() {
public void run() {
//Showing some UI elements
}
});
}
}
So, how can I globally initialize the Activity and my plugin class in Unity one time, and use them in all of my scripts?
As discussed in the comments, I recommend using the singleton pattern.

javafx db load progress indicator

private Popup popupProgressIndicator;
public void showProgressIndicator(ScreensController myController) {
if (popupProgressIndicator == null) {
ProgressIndicator indicator = new ProgressIndicator(-1.0);
indicator.setPrefHeight(200);
indicator.setPrefWidth(200);
indicator.setLayoutX(0);
indicator.setLayoutY(0);
popupProgressIndicator = new Popup();
popupProgressIndicator.getContent().add(indicator);
}
if (!popupProgressIndicator.isShowing()) {
popupProgressIndicator.show(primaryStage);
popupProgressIndicator.centerOnScreen();
}
myController.setDisable(true);
}
public void hideProgressIndicator(ScreensController myController) {
if (popupProgressIndicator.isShowing())
popupProgressIndicator.hide();
myController.setDisable(false);
}
Hi I'm using above code for creating progress indicator in javafx app.
I want to show a progress indicator while loading data from db or saving data to db.
#FXML
private void addDesignationSelect() {
showProgressIndicator(myController);
Task<Void> task = new Task<Void>() {
#Override
protected Void call() throws Exception {
Platform.runLater(new Runnable() {
#Override
public void run() {
// doing some heavy db process
}
});
return null;
}
#Override
protected void succeeded() {
hideProgressIndicator(myController);
}
#Override
protected void failed() {
super.failed();
hideProgressIndicator(myController);
}
};
new Thread(task).start();
}
I have used Task for loading progress bar, but it is not showing the progress bar. What I am doing wrong?
You call show your method showProgressIndicator before you start your Thread/Task. This is the reason why your window is not shown (or shown for a very short time)
You could open the progressBar and after myController.setDisable(true);, you can wait if the task returns a specific value (use Task<Boolean> for example).
The method isDone() will tell you when your Task has end and when to call hideProgressIndicator.
Another option would be to do the UI-Modifications from your Task itself, see the example here Task

Ad Colony ads run just one time

Problem : Whenever I run application on a new mobile, my ad loads and runs perfectly where I want it to run. But after that on same mobile ad video doesn't play, even after I un-install my application and install again.
I don't want to show ads on my main activity, but I want to load ads in that activity. That's why I have added this in my main activity class
implements AdColonyAdListener, AdColonyAdAvailabilityListener
and override its methods like this.
#Override
public void onAdColonyAdAvailabilityChange(boolean isAvailable, String arg1) {
AdColonyHelper.isAdvAvailable = isAvailable;
}
#Override
public void onAdColonyAdAttemptFinished(AdColonyAd arg0) {
}
#Override
public void onAdColonyAdStarted(AdColonyAd arg0) {
}
To track the availability of ad I have a static boolean variable in my AdColonyHelper class. AdColony Helper class:
package Helpers;
import android.app.Activity;
import com.jirbo.adcolony.AdColonyAdListener;
import com.jirbo.adcolony.AdColonyVideoAd;
public class AdColonyHelper {
public static boolean isAdvAvailable = false;
public static String APP_ID;
public static String ZONE_ID;
static Activity act = new Activity();
public static void setting(String appid, String zoneId, Activity myAct)
{
APP_ID = appid;
ZONE_ID = zoneId;
act = myAct;
}
public static void showAdv(boolean isAvailable)
{
isAdvAvailable = isAvailable;
if(isAdvAvailable)
{
AdColonyVideoAd ad = new AdColonyVideoAd(ZONE_ID);//.withListener( (AdColonyAdListener) act );
ad.show();
}
}
public static void showAdv()
{
if(isAdvAvailable)
{
AdColonyVideoAd ad = new AdColonyVideoAd(ZONE_ID).withListener( (AdColonyAdListener) act );
ad.show();
}
}
}
in on create of my main activity I initialize it like this
AdColony.configure( this, "version:1.0,store:google", APP_ID, ZONE_ID );
AdColony.addAdAvailabilityListener(this);
if ( !AdColony.isTablet() )
{
setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT );
}
// below line is to set static variables in class
AdColonyHelper.setting(APP_ID, ZONE_ID, this);
This is all what I have done for ads in my main activity. Now right after going to my second Activity. I have this in on create method of that activity.
AdColonyHelper.showAdv();
This checks the availability of ad and plays it. But it plays ad just only one time.
But I continuously see this in my logcat
01-08 14:12:15.579: I/AdColony(23623): Finished downloading:
01-08 14:12:15.609: I/AdColony(23623): https://androidads21.adcolony.com/configure?......

AsyncTask handle message recieved by another class and update progress

My problem is this;
I have a AsyncTask that works fine, and on doInBackground() it calls a new class that sync my data to a web service using REST service, i don't have everything on a unique class because i need the same content sync for different activitys and it's easier this way.
What i need is, on the sync procedure, i can get the number of "contacts" and everytime it downloads a contact, removes 1 from the "contacts" lenght, so, i nedd to show on the progress dialog the length of contact and refresh everytime it downloads a new "contact"
hre's my code for the AsyncTask:
public class syncContentTask extends AsyncTask<String, String, Boolean> {
private ProgressDialog mprogress;
private Context context;
//token for JSON header to authenticate
String authToken;
public syncContentTask(Context cxt, String token) {
this.context = cxt;
mprogress = new ProgressDialog(context);
authToken = token;
}
protected void onPreExecute() {
mprogress = ProgressDialog.show(context, "Sync", "Sync in progress...");
}
#Override
protected Boolean doInBackground(String... params) {
syncData syncData = new syncData();
syncData.syncData(context, authToken);
publishProgress(progress);
return true;
}
protected void onProgressUpdate(String... progress) {
//mprogress.setProgress(Integer.parseInt(progress[0]));
}
protected void onPostExecute(Boolean result) {
if (result) {
mprogress.dismiss();
}
}
}
In the Sync Data class i have functions that handles the HttpRequest and database stuff...
can anyone help??
You need to create a listener for your data progress and have it update the progress bar. Right now it looks like this line:
syncData.syncData(context, authToken);
blocks and no updates are provided to your progress indicator until it is done. So, you need something like:
MyListener listener = new MyListener(context);
SyncData syncData = new syncData(listener);
And in your listener have callback methods like myListener.downloadStarted() , myListener.updateProgressBar(int progress) and myListener.downloadCompleted() that your syncData class calls as the download progresses.
For example:
public abstract class SDScanAdapter implements SDScanListener {
public void startScan() {
}
public void updateScanProgress(int scanItemsTotal, int scanItemsCompleted) {
}
public void scanComplete() {
}
}
Then create a listener class:
public class ScanListener extends SDScanAdapter {
#Override
public void scanComplete(String contactName, String action) {
runOnUiThread(scanComplete);
}
#Override
public void startScan() {
runOnUiThread(startScan);
}
#Override
public void updateScanProgress(int scanItemsTotal,
int scanItemsCompleted) {
if (scanCountTotal != scanItemsTotal) {
scanCountTotal = scanItemsTotal;
progressBar.setMax(scanCountTotal);
}
if (scanCountUpdate != scanItemsCompleted) {
scanCountUpdate = scanItemsCompleted;
runOnUiThread(updateScanProgress);
}
}
}
And then for this example you need Runnables (startScan, scanComplete and updateScanProgress) that perform UI tasks, like updating the progress bar. In your case, you may also want to load some of the results, etc.
Then in your AsyncTask you do:
ScanListener listener = new ScanListener();
SyncData syncData = new syncData(listener);
Assuming the SDScanListener class and AsyncTask are all in your Activity. Also, your SyncData calss will need to have a SDScanListener variable that is set when it instantiates. Then, while it does its job, calls are made to the listener methods like:
scanListener.startScan();
And while it progresses, it calls the other methods (and corresponding parameters are passed in).

Categories