Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Call method from main class within JavaScriptInterface

Tags:

android

I'm relatively new to android development and I'm trying to make a WebView that will allow me to launch the android camera app. How can I go about calling a method in the main class from with my JavaScriptInterface?

Thanks.

public class MainActivity extends Activity {

    public static final int MEDIA_TYPE_IMAGE = 1888;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
        mainWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
        WebSettings webSettings = mainWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        mainWebView.setWebViewClient(new MyCustomWebViewClient());
        //mainWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

        mainWebView.loadUrl("file:///mnt/sdcard/page.html");
    }

    private class MyCustomWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }



    public void takePicture() {
        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, MEDIA_TYPE_IMAGE);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (requestCode == MEDIA_TYPE_IMAGE) {  
            Bitmap photo = (Bitmap) data.getExtras().get("data"); 


            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            }}

    }



package com.cargowise.view;

import android.content.Context;
import android.os.Handler;
import android.widget.Toast;

public class JavaScriptInterface {



    Context mContext;

    /** Instantiate the interface and set the context */
    JavaScriptInterface(Context c) {
        mContext = c;
    }


    public void takePic() {
        MainActivity.takePicture();
    }


    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }

1 Answers

You have stored the context which you should be able to use to access your MainActivity.

Change this:

public void takePic() {
    MainActivity.takePicture();
}

To this:

public void takePic() {
    ((MainActivity)mContext).takePicture();
}

Note: you might want to add some type-checking or limit the type of the context that is given to a MainActivity to enforce correct behavior.

like image 57
cklab Avatar answered Jan 29 '26 23:01

cklab