Search code examples
androidandroid-intentwait

Activity wait for Intent


What I'm trying to do


Hello Guys, I'm trying to create a SplashScreen which starts a Service over an Intent. After the Service is started to Activity(SplashScreen) should wait until it receive an Intent from my Service.

Question


What do I need to do, that my Activity waits until it received the Intent from my Service. It would be nice if you could provide me a good tutorial or some code-snippets. Down here you find the Code of my SplashScreen.

Code


package de.stepforward;

import de.stepforward.service.VideoService;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class SplashActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        // Sagt dem Video-Service das er beginnen soll die
        // Videos herunter zu laden
        Intent LoadVideos = new Intent(this, VideoService.class);
        LoadVideos.putExtra("VIDEO_SERVICE", "start");
        startService(LoadVideos);

        // In this thread I want that it waits for my Intent
        // and than it goes to the next Activity
        Thread splashThread = new Thread() {

            @Override
            public void run() {
                try {
                    int waited = 0;
                    while (waited < 3000) {
                        sleep(100);
                        waited += 100;
                    }
                }
                catch (InterruptedException e) {
                    // do nothing
                }
                finally {
                    finish();
                    final Intent Showvideo = new Intent(SplashActivity.this,
                                                        ChannelTest.class);
                    startActivity(Showvideo);
                }
            }
        };
        splashThread.start();
    }
}

Solution

  • Here is what your architecture should look like :

    INTENT_CST


    String START_INIT_ACTION = "your.package.name.START_INIT";
    String INIT_ENDED_ACTION = "your.package.name.INIT_ENDED";
    

    SplashActivity


    In onCreate:

    startService(new Intent(START_INIT_ACTION)
    

    In onResume:
    If you choose to send a broadcast in your service :

    registerReceiver(new BroadcastReceiver(){
        //implement onChange()},
        new IntentFilter(INIT_ENDED_ACTION));
    

    In onPause, unregister your receiver to free memory

    LoadingService


    Extend AsyncTask to do your background stuff. In onPostExecute, 2 options :

    startActivity(new Intent(...)) // as your doing in your post
    

    or

    sendBroadcast(new Intent(INIT_ENDED_ACTION)); stopSelf();
    

    Your manifest


    Declare the service LoadingService with an IntentFilter with an <action name="your.package.name.START_INIT"/>