【问题标题】:How to pass a value in Services?如何在服务中传递值?
【发布时间】:2011-03-08 07:01:12
【问题描述】:

我正在制作一个可以在后台运行的媒体播放器。我必须在这个服务中发送一个字符串 uri。 但我无法通过 bundle.Services 类从我的活动中发送 uri 值不支持 getIntent() 并显示错误。 我如何通过活动发送 uri 服务。 请帮忙

package com.abc.activity;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {
    private static final String TAG = "MyService";
    MediaPlayer player;
    String uri,url;
    Bundle b;
    AudioPlayer2 ap;


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

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate");

        Uri path=Uri.parse("/mnt/sdcard/download/abc.mp3");
        player = MediaPlayer.create(this,path );
        player.setLooping(false); // Set looping
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");
        player.stop();
    }

    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");
        //Bundle extras = getIntent().getExtras();
        player.start();
    }
    public void getValue(String uri)
    {
        url=uri;
    }
}

这适用于我在本示例中使用的静态 url。请建议我可以从我的活动类中获取 uri 的值。Bundle 在此类中不起作用

【问题讨论】:

    标签: android service android-activity android-intent


    【解决方案1】:

    您应该使用 IntentService http://developer.android.com/reference/android/app/IntentService.html

    实现onHandleIntent(Intent intent),每次使用startService(intent) 启动服务时都会调用它。您可以通过此意图将数据传递给服务。

    【讨论】:

      【解决方案2】:

      如果您尝试将字符串或字符串数​​组从一个 Activity 发送到另一个 Activity,这可以在 Intent 中完成。

      在A类中:

      Intent intent = new Intent(this, ClassB);
      tring[] myStrings = new String[] {"test", "test2"};
      intent.putExtra("strings", myStrings);
      startActivity(intent);

      在 B 类中:

      public void onCreate() {
      Intent intent = getIntent();
      String[] myStrings = intent.getStringArrayExtra("strings");
      }

      【讨论】:

      • 我想将一个活动的字符串发送到我的服务类。这不是活动..
      • 是的,您可以从一个活动访问字符串到任何其他活动(它可以服务类或其他活动)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-05
      • 2011-05-06
      • 1970-01-01
      相关资源
      最近更新 更多