简体   繁体   中英

How do I access the main webview instance from another Activity in my Android app?

I created an Android app with PhoneGap. The MainActivity looks like this:

MainActivity.java

import org.apache.cordova.*;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends DroidGap {
      @Override
      public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        super.loadUrl("file:///android_asset/www/index.html");
      }
}

Also, I have another activity which gets called when a certain JavaScript event within my index.html happens. In this case, onCreate(Bundle b) gets called:

MyUriActivity.java

import android.app.Activity;
import android.os.Bundle;

public class MyUriActivity extends Activity {
    @Override
    public void onCreate(Bundle b){
        super.onCreate(b);

        // I want to access appView here, so I can call
        // appView.loadUrl("file:///android_asset/www/index.html");
    }
}

As shown in the comment above, I want to re-open index.html when this event occurs but I don't know how to access the webview instance.

How do I do this?

To communicate between your two actions, you should use Intents

They allow you to put custom data in a message and send it to another Action, something like this:

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "News for you!");
startActivity(intent);

M. Lars Vogel has a ton of nice examples on this (the one above is taken from his blog

http://www.vogella.com/articles/AndroidIntent/article.html

If I understand your question correctly, you want to have MainActivity display something (the already loaded WebView) when something happends in MyUriActivity. You should create an intent in MyUriActivity that you then send to MainActivity.

This may not be the most elegant solution, but you should give it a try.

Since both are your apps, create a getFile() method in MainActivity and return the required File (not just URL, you need to return the File). Then use reflection from MyUriActivity to access this getFile() method, and you should be able to get the required file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM