17

I have an Android service that is running and listening for microphone input. I want it to launch an activity when a certain criteria is met. In order to create an Intent I need the application context. How can I get it?

Intent i = new Intent(ctx, SONR.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(i);

The above line does not start my activity.

Here is my constructor

public SONRClient(Context c, AudioRecord ar, int buffsize, final AudioManager am) {
    theAudioManager = am;
    theaudiorecord = ar;
    bufferSize = buffsize;
    ctx = c;
    CLIENT_ON = true;
}

Here is my onCreate

@Override
public void onCreate() {
    try {
        // LogFile.MakeLog("\n\nSONRClient CREATED");
        clientStopReceiver = new StopReceiver();
        ctx.registerReceiver(clientStopReceiver, 
            new IntentFilter(SONR.DISCONNECT_ACTION));
        myByteReceiver = new SONRByteReceiver();
        theListener = new MicSerialListener(
            theaudiorecord, bufferSize, myByteReceiver);
        theApplication = getApplication();
    } catch (Exception e) {
        e.printStackTrace();
        ErrorReporter.getInstance().handleException(e);
    }
}

There is myByteReceiver that is listening for signals via audio input. When it finds a matching signal, I want it to launch an activity.

private class SONRByteReceiver implements ByteReceiver {
    private long lastplaytime = 0;
    private long lastmutetime = 0;
    private long lastskiptime = 0;
    private long lastvolutime = 0;
    private long lastbacktime = 0;

    public void receiveByte(int receivedByte) {
        try {
            theKeyEvent = -1;

            if (ismuted) {
                if (receivedByte != MUTE) {
                    volume = 0;
                    ismuted = false;
                }
            }

            switch (receivedByte) {

            case SONR_HOME:
                Log.d(TAG, "HOME");

                Intent i = new Intent(ctx, SONR.class);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                theApplication.startActivity(i);

                break;
            default:
                Log.d(TAG, "default");
                Log.d(TAG,"RECEIVED " + receivedByte);
                // LogFile.MakeLog("RECEIVED " + receivedByte);
                break;
            }

            if (theKeyEvent >= 0) {
                sendbroadcast();
            }
        } catch (Exception e) {
            e.printStackTrace();
            ErrorReporter.getInstance().handleException(e);
        }
    }
}

Here is the stacktrace

java.lang.NullPointerException
    at com.sonrlabs.test.sonr.SONRClient$SONRByteReceiver.receiveByte(SONRClient.java:320)
    at com.sonrlabs.test.sonr.AudioProcessor.processSample(AudioProcessor.java:145)
    at com.sonrlabs.test.sonr.AudioProcessor.run(AudioProcessor.java:58)

Line 320 is theApplication.startActivity(i);

JJD
  • 50,076
  • 60
  • 203
  • 339
Sheehan Alam
  • 60,111
  • 124
  • 355
  • 556
  • 1
    Could you post the method you call `getApplicationContext` in? – skynet Nov 29 '11 at 03:46
  • It would be more helpful if you posted the log of the NullPointerException you are getting. – keno Nov 29 '11 at 05:39
  • None of your code seems to assign anything to the ctx variable. Review your code to see where "ctx" is assigned a value and do some print outs around the assignment to see when and if it is ever assigned. – keno Nov 29 '11 at 14:42
  • ctx is assigned, in my constructor. i can post that code as well – Sheehan Alam Nov 29 '11 at 16:12
  • I also print out the package name from my context. And it does it fine. Problem is in startActivity. Not sure why. – Sheehan Alam Nov 29 '11 at 16:28
  • Only other thing I can think of atm is that your SONR activity may not be defined in your manifest. – keno Nov 29 '11 at 20:41
  • Can you post the code which calls the SONRClient constructor? It seems you are passing a null value into this constructor. – Matt Accola Jun 14 '12 at 06:16

9 Answers9

6

You can use getApplicationContext() inside your service to get the application context.

Try using

getApplication().startActivity(i);

android start activity from service

Community
  • 1
  • 1
skynet
  • 9,898
  • 5
  • 43
  • 52
5

Every Service has its own Context, just use the that. You don't need to pass a Service an Activity's Context.

No need for activity context in Service.

Intent i = new Intent(ctx, SONR.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);

Simply do as you do in Activity

Service and Activity both are subclasses of Context.

Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
2

Change this:

Intent i = new Intent(ctx, SONR.class); 

to:

Intent i = new Intent(getApplicationContext(),SONR.class);
bluish
  • 26,356
  • 27
  • 122
  • 180
Rohit
  • 593
  • 2
  • 8
  • Impossible, You are getting null pointer exception somewhere else. If your service is running then context cant be null. – Rohit Nov 29 '11 at 09:43
  • Try to click on this line : at com.sonrlabs.test.sonr.AudioProcessor.processSample(AudioProcessor.java:145) or line above n below that, to find whr u r getting null. – Rohit Nov 30 '11 at 04:20
1

getBaseContext() which returns context since every activity extends Context class

1

You mustn't call to getApplicationContext() inside its public empty constructor, or it will give you a NullPointerException.

JJD
  • 50,076
  • 60
  • 203
  • 339
joninx
  • 1,775
  • 6
  • 31
  • 59
1

You're assertion that you need an application context to start an activity is inaccurate. You can start an activity from any context, including the service, which is a context.

dhaag23
  • 6,106
  • 37
  • 35
  • I tried it using just startActivity(), I still get a nullpointerexception. Updated question with more code – Sheehan Alam Nov 29 '11 at 05:12
  • Show the stack track for the null pointer. It's not because of a null service if you're using it from within that class. – dhaag23 Nov 29 '11 at 16:25
  • The stacktrace in the question is all that is printed when I am debugging. Any ideas on how to debug further? – Sheehan Alam Nov 29 '11 at 16:28
0

There is a not null context only after 'onCreate()' of the Service : getting the context of the service in the constructor is not a good idea (not yet any context), get it with the simple 'getApplicationContext()' in the 'onCreate' method.

g910
  • 96
  • 3
-1

Just do this to access the Service context

Intent i = new Intent(Service.this, SONR.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
-2
ctx.getApplicationContext().startActivity(i)

boom.

Sheehan Alam
  • 60,111
  • 124
  • 355
  • 556