Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android startActivity from JavascriptInterface

Simple general question.

Webview is hooked up to my JavascriptInterface class and it is most certainly functional. However, because JavascriptInterface does not extend Activity, I cannot seem to Intent to a new activity using startActivity(intent);

Should I extend Activity? Is there another method to intent to another activity? (in my very special case, im trying to intent to the YouTube app)

package com.privateized.moreprivate;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;

public class JavaScriptInterface {
    Context mContext;

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

    /** Show a toast from the web page */
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }



    ///// vvvvv This no Worky vvvvv Just crashes ////////
    public void YouTube(String id) {
        Log.d("JS", "Launching YouTube:" + id);
        Activity activity = new Activity();
        String videoId = id;
        Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:"+videoId)); 
        i.putExtra("VIDEO_ID", videoId); 
        Log.d("JS", "Starting Activity");
        activity.startActivity(i);
    }

}
like image 633
RedactedProfile Avatar asked Oct 21 '25 02:10

RedactedProfile


1 Answers

Just use mContext.startActivity(i);

No need to ever create Activity and no need to extend Activity, you just need a reference to Context which you already have stored.

like image 78
sgarman Avatar answered Oct 22 '25 17:10

sgarman