Dmitry
Dmitry

Reputation: 11

Dialog: MyActivity has stopped

I study services on Android and in the example I came across a code in which after a while a message comes from the service. But I can’t understand why I get the dialog "MyActivity has stopped" (link to the image below) instead of a notification. I found the reason and this is the commented out line:

//Toast.makeText(this, "onCreate: Service work!", Toast.LENGTH_SHORT).show();

My code:

public class MyService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
        //Toast.makeText(this, "onCreate: Service work!", Toast.LENGTH_SHORT).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            TimeUnit.SECONDS.sleep(3);
            Toast.makeText(MyService.this, "onStartCommand: Ding!", Toast.LENGTH_SHORT).show();
        }catch (InterruptedException ex){
            ex.printStackTrace();
        }
        return super.onStartCommand(intent, flags, startId);
    }
}

I started my servece from:

startService(new Intent(this,MyService.class));

In my AndroidManifest service registred as:

<service android:name=".MyService" android:process=":com.myService"/>

Question:

Please explain why I get this message when I use Toast in onCreate().

https://i.sstatic.net/VlHQ9.png

Upvotes: 0

Views: 45

Answers (1)

Zohaib Amir
Zohaib Amir

Reputation: 3562

Your service might be in a different thread. Use handler to show Toast:

Handler handler = new Handler();
Runnable toastRunnable = new Runnable(){ 
@Override public void run() { 
Toast.makeText(MyService.this, "onCreate: Service work!", Toast.LENGTH_SHORT).show(); 
    } 
};

handler.post(toastRunnable);

Upvotes: 1

Related Questions