显示吐司的 Android 服务 [英] Android Service to show toast

查看:24
本文介绍了显示吐司的 Android 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码应该使用服务来显示 Toast 消息.没有错误,但不显示 Toast.

This code is supposed to use a service to show a toast message. There are no errors, but it doesn't show the toast.

主要活动

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



}

清单

<?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>

推荐答案

查看文档的这一部分

(IntentService 有一些限制:

(An IntentService has a few limitations:

它无法直接与您的用户界面交互.把它的结果在 UI 中,您必须将它们发送到 Activity.

It can't interact directly with your user interface. To put its results in the UI, you have to send them to an Activity.

你需要把它放在主Thread上.请参阅 此处由 rony 提供的答案这样做.

You need to put it on the main Thread. See the answer here by rony of a way to do that.

以及来自 IntentService 的完整文档

使用工作线程依次处理每个 Intent

handles each Intent in turn using a worker thread

这篇关于显示吐司的 Android 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆