jmease jmease - 4 months ago 28
Android Question

Android Start Activity from Class

public class WeeklyInspection : Activity
{
WebView view = (WebView) FindViewById(Resource.Id.inspectionWV);
view.Settings.JavaScriptEnabled = true;
view.Settings.CacheMode = CacheModes.CacheElseNetwork;
view.SetWebChromeClient(new CustomWebChromeClient(this));
view.SetWebViewClient(new CustomWebViewClient(this));
view.LoadUrl("http://myurl.com");
}

private class CustomWebChromeClient: WebChromeClient
{
public override void OnConsoleMessage(string message, int lineNumber, string sourceID)
{
if (message.StartsWith("Submit")
//do all my submit stuff here
//if without error, I want to go back to the Main Activity. Have tried:
Intent intent = new Intent(BaseContext, typeof(Main));
StartActivity(intent); //Both BaseContext and StartActivity throw "Cannot access non-static method in static context"
//tried:
Finish(); //Same thing
//tried:
OnBackPressed(); //Same thing
}
}

Answer

As the compiler error message you encountered states, StartActivity is an instance method of Context, not a static method, and therefore cannot be called like that.

You didn't include it in the code sample, but in the activity you pass "this" (the activity) into the constructor to CustomWebChromeClient, so I'm assuming CustomWebChromeClient is keeping a reference to it. You can use that reference to call the instance methods you need on the activity, whether it be StartActivity, Finish, or whatever else you need. For example:

private class CustomWebChromeClient: WebChromeClient
{
    private readonly Activity _context;

    public CustomWebChromeClient(Activity context) 
    {
        _context = context;
    }

    public override void OnConsoleMessage(string message, int lineNumber, string sourceID)
    {
        if (message.StartsWith("Submit"))
        {
            _context.Finish();
        }
    }
}
Comments