Question

In Service of Keyboard i cant start Main Activity:

public void onKey(int primaryCode, int[] keyCodes) 
    Log.d(TAG, primaryCode + " PrimaryCode to send");
    if (primaryCode == 6) {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        Log.d(TAG, primaryCode + " Greating is command");
    } 

As a result, an error pops up

LogCat:

12-03 10:46:07.613: E/InputEventReceiver(2776): Exception dispatching input event.
12-03 10:46:07.613: E/MessageQueue-JNI(2776): Exception in MessageQueue callback: handleReceiveCallback
12-03 10:46:07.613: E/MessageQueue-JNI(2776): android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
12-03 10:46:07.613: E/MessageQueue-JNI(2776):   at android.app.ContextImpl.startActivity(ContextImpl.java:944)
12-03 10:46:07.613: E/MessageQueue-JNI(2776):   at android.app.ContextImpl.startActivity(ContextImpl.java:931)
12-03 10:46:07.613: E/MessageQueue-JNI(2776):   at android.content.ContextWrapper.startActivity(ContextWrapper.java:284)
12-03 10:46:07.613: E/MessageQueue-JNI(2776):   at sample.stand.Keyb.onKey(Keyb.java:162)
Was it helpful?

Solution

In the logCat, he suggests to use FLAG_ACTIVITY_NEW_TASK flag , so try the following:

if (primaryCode == 6) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
    Log.d(TAG, primaryCode + " Greating is command");
} 

OTHER TIPS

Change in the Manifest.xml from

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

as

        <intent-filter>
            <action android:name="android.intent.action.MAINACTIVITY" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

And call from yours Intent as,..

        Intent intent = new Intent("android.intent.action.MAINACTIVITY");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        startActivity(intent);

Try this..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top