Android将数据从类传递到服务

时间:2017-05-12 21:37:08

标签: android

如何将字符串的值从类传递给后台服务?我已经创建了android应用程序来从url读取ip地址,我想将textResult字符串中的值传递给后台服务中的STREAM_URL!我怎么能这样做?

public class BackgroundService extends Service implements OnCompletionListener
{
    MediaPlayer mediaPlayer;
    private String STREAM_URL;
    final String textSource = "http://audiophileradio.stream/Ip.txt";

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

    @Override
    public void onCreate()
    {

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        new MyTask().execute();

        return START_STICKY;
    }

    public void onDestroy() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.release();
    }

    public void onCompletion(MediaPlayer _mediaPlayer) {
        stopSelf();
    }


    @Override
    public boolean onUnbind(Intent intent)
    {
        return super.onUnbind(intent);
    }

    private class MyTask extends AsyncTask<Void, Void, String>
    {
        String textResult;

        @Override
        protected String doInBackground(Void... params) {

            URL textUrl;

            try {
                textUrl = new URL(textSource);

                BufferedReader bufferReader
                        = new BufferedReader(new InputStreamReader(textUrl.openStream()));

                String StringBuffer;
                String stringText = "";
                while ((StringBuffer = bufferReader.readLine()) != null) {
                    stringText += StringBuffer;
                }
                bufferReader.close();

                textResult = stringText;
                return textResult;
            } catch (MalformedURLException e) {
                e.printStackTrace();
                textResult = e.toString();
            } catch (IOException e) {
                e.printStackTrace();
                textResult = e.toString();
            }

            return null;

        }

        @Override
        protected void onPostExecute(String result) {

            Log.d("DebugTag", "Value: " + textResult);

            super.onPostExecute(result);

            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(BackgroundService.this);
            String radio = sharedPreferences.getString("station", "8000");

            if (radio != null && radio.equals("8000"))
            {
                STREAM_URL = "http://178.149.88.126:8000/";
            }
            if (radio != null && radio.equals("8010"))
            {
                STREAM_URL = "http://178.149.88.126:8010/";
            }
            if (radio != null && radio.equals("8020"))
            {
                STREAM_URL = "http://178.149.88.126:8020/";
            }
            if (radio != null && radio.equals("8030"))
            {
                STREAM_URL = "http://178.149.88.126:8030/";
            }

            mediaPlayer = new MediaPlayer();

            if (!mediaPlayer.isPlaying())
            {
                try
                {
                    mediaPlayer.reset();
                    mediaPlayer.setDataSource(STREAM_URL);
                    mediaPlayer.prepareAsync();

                    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
                    {
                        @Override
                        public void onPrepared(MediaPlayer mp)
                        {
                            mediaPlayer.start();
                        }
                    });
                } catch (IOException e)
                {
                    e.printStackTrace();
                }

            }

            mediaPlayer.setOnCompletionListener(BackgroundService.this);
        }
    }

}

2 个答案:

答案 0 :(得分:1)

在aynctask的opPostExecute上,您可以使用结果字符串。 UI线程。您还可以在类中设置一个全局变量,并使用onPostExecute中的值进行设置。

BEGIN {
  x=SUBSEP

  # How can I take these strings...
  a_keys = "Red.Green.Blue"
  b_keys = "Yellow.Cyan.Purple"

  # .. And populate the array, just as this does:
  a="Red" x "Green" x "Blue"
  b="Yellow" x "Cyan" x "Purple"

  Colors[1][0] = ""
  Colors[2][0] = ""

  split(a, Colors[1], x)
  split(b, Colors[2], x)

  print Colors[2][3]
}

答案 1 :(得分:0)

使用广播接收器的另一种方式是示例

    import android.app.Service;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.support.annotation.Nullable;


    public class TempService extends Service {

        BroadcastReceiver broadcastReceiver;

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

        @Override
        public void onCreate() {
            super.onCreate();
            broadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    if (intent != null && intent.getAction().equals("UpdateUrl")) {
                        Bundle bundle = intent.getExtras();
                        if (bundle != null && bundle.containsKey("urlNew")) {
                            String newUrl = bundle.getString("urlNew");
                        }
                    }
                }
            };
            IntentFilter intentFilter = new IntentFilter("UpdateUrl");
            registerReceiver(broadcastReceiver, intentFilter);

        }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if(broadcastReceiver!=null){
            unregisterReceiver(broadcastReceiver);
        }
    }

    }

从更新放置下面的代码,

Intent intent = new Intent();
intent.setAction("UpdateUrl");
intent.putExtra("urlNew", "" + newUrl);
sendBroadcast(intent);