0

I am creating an android app for a client using a WebView. There are some links on the client's website that play media. In order to conserve battery, I am trying to call the "FLAG_KEEP_SCREEN_ON" when a user clicks on this media link within the website. My webview uses a new MywebViewClient() in order to handle the loading of webpages inside the webview. MywebViewClient is actually a private class that overrides shouldOverrideUrlLoading(). Since this method detects when the user clicks on the link that plays media files, I tried to apply "FLAG_KEEP_SCREEN_ON". If it is not one of the pages that plays media files , I clear "FLAG_KEEP_SCREEN_ON". The problem I am having is that since this method is inside a private class, I can't seem to get a reference for my Activity. Perhaps the call: getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); doesn't know which window to apply this flag to. I am sure its probably something minor, but I just cant seem to get the Activity that hosts the windows from inside this inner class. Here is my code so far:

Webview w;
//inside onCreate
{

w.setWebViewClient(new WebViewClient());

}  

private class MyWebViewClient{

if (Uri.parse(url).getHost().equals("WebsitesHost")) {

        if(w.getUrl().equals("LinkThatPlaysMediaSound" && 
   !getWindow.hasFeature(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)){

    getWindow.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

}

if(!w.getUrl().equals("LinkThatPlaysMediaSound")
    getWindow.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        return false;
    }


    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    startActivity(intent);
    return true;
}




}
i_o
  • 777
  • 9
  • 25
  • Did you try outerclass.this where outerclass is your activity name and "this" will give you the activity instance – Ankit Aggarwal May 02 '16 at 16:14
  • I can try that. But, I think then I will have to change the call getWindow.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) to OuterClass.this.getWindow.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) I don't know if this call will work. @AnkitAggarwal – i_o May 02 '16 at 16:21

1 Answers1

0

Add a constructor to the MyWebViewClient which takes Activity instance.

private MyWebViewClient(Activity activity)
{
    this.activity = activity;
}

Pass the activity instance while creating the MyWebViewClient

new MyWebViewClient(this);

If your inner class is not static(but you consider using static), you could simple use, YourActivityName.this for activity instance.

Bob
  • 13,447
  • 7
  • 35
  • 45