Sheehan Alam
Sheehan Alam

Reputation: 60869

How can I get the application context from an Android Service?

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);

Upvotes: 17

Views: 55175

Answers (9)

g910
g910

Reputation: 96

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.

Upvotes: 0

DipDro420
DipDro420

Reputation: 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);

Upvotes: -1

joninx
joninx

Reputation: 1780

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

Upvotes: 1

Zar E Ahmer
Zar E Ahmer

Reputation: 34360

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.

Upvotes: 5

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

Upvotes: 1

Rohit
Rohit

Reputation: 603

Change this:

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

to:

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

Upvotes: 2

Sheehan Alam
Sheehan Alam

Reputation: 60869

ctx.getApplicationContext().startActivity(i)

boom.

Upvotes: -2

dhaag23
dhaag23

Reputation: 6126

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.

Upvotes: 1

skynet
skynet

Reputation: 9908

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

Try using

getApplication().startActivity(i);

android start activity from service

Upvotes: 6

Related Questions