This code is supposed to use a service to show a toast message. There are no errors, but it doesn't show the toast.
main activity
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent i= new Intent(this, BackgroundMusic.class); this.startService(i); } }
service (its called Background Music but for now it is supposed to show a toast message)
public class BackgroundMusic extends IntentService { public BackgroundMusic() { super("BackgroundMusic"); } @Override protected void onHandleIntent(Intent intent) { // Normally we would do some work here, like download a file. // For our sample, we just sleep for 5 seconds. Context context = getApplicationContext(); CharSequence text = "Hello toast!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } }
manifest
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.starwars" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:debuggable="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <service android:name=".BackgroundMusic" /> <activity android:name="com.example.starwars.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:label="@string/app_name" android:name="BackgroundMusic"/> </application> </manifest>
To display a simple Toast message, we can do the following. // Declare the parameters to use for the Toast Context context = getApplicationContext(); // in an Activity, you may also use "this" // in a fragment, you can use getActivity() CharSequence message = "I'm an Android Toast!"; int duration = Toast.
Display the created Toast Message using the show() method of the Toast class. The code to show the Toast message: Toast. makeText(getApplicationContext(), "This a toast message", Toast.
Try this:
new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Toast.makeText(YourService.this.getApplicationContext(),"My Awesome service toast...",Toast.LENGTH_SHORT).show(); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With