Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

javascript - How to call an Android Activity from PhoneGap

I am new to PhoneGap and I am able to implement the basic app with PhoneGap, now to enhance it further, I want to connect PhoneGap with Android Activities, basically what I plan is to call startActivity() method using a javascript function.

I tried Communication between Android Java and Phonegap Javascript?

but I failed to call an activity, causing force close error. Do help me out, awaiting a reply!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Any Java Native code call be called without using any plugin as following.

Follow The following Steps.

  1. Replace the following code with your existing DroidGap Activity.

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.init(); // Calling this is necessary to make this work
        appView.addJavascriptInterface(this, "MainActivity");
    
        /* "this" points the to the object of the current activity. "MainActivity" is used to refer "this" object in JavaScript as in Step 3. */
    
        super.loadUrl("file:///android_asset/www/index.html");
    }
    
  2. Add the custom function in current (this) activity as following.

    public void customFunctionCalled() {
        Log.e("Custom Function Called", "Custom Function Called");
    }
    
  3. Now call this function from your HTML/JavaScript code as following.

    <script type="text/javascript">
        function callNewActivity() {
            window.MainActivity.customFunctionCalled();
        }
    </script>
    

This will call customFunctionCalled() in MainActivity.

Tested Environment Eclipse - 3.7.2 Android 2.2 Emulator PhoneGap - 2.0.0

Please provide your comments here to improve blogs post. http://phonegapexplorers.blogspot.in/2012/08/call-native-java-code-phonegap-android.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...