Android服务展示吐司

cod*_*erx 36 service android toast

此代码应该使用服务来显示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); 

}



}
Run Code Online (Sandbox Code Playgroud)

服务(它被称为背景音乐,但现在它应该显示一个祝酒词)

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



}
Run Code Online (Sandbox Code Playgroud)

表现

<?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>
Run Code Online (Sandbox Code Playgroud)

Gal*_*Rom 80

试试这个:

Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {

    @Override
    public void run() {
            Toast.makeText(YourService.this.getApplicationContext(),"My Awesome service toast...",Toast.LENGTH_SHORT).show();
            }
        });
Run Code Online (Sandbox Code Playgroud)

  • 它确实展示了吐司,但它会一直保持屏幕亮 (3认同)

cod*_*gic 22

请参阅文档的这一部分

(IntentService有一些限制:

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

你需要把它放在主要的Thread.请看rony这里的答案.

并从IntentService完整文档

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