How to pass a value in Services?

2020-04-01 18:44发布

问题:

I am making a media player ,who can run in background. i have to send a string uri in this service. but i cant send the uri value from my activity through bundle.Services class doesnot support getIntent() and show error. how can i send uri in service through activity. please help

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

This is working with static url which i use in this example. please suggest what can i fetch uri's value from my activity class.Bundle is not working in this class

回答1:

You should use IntentService http://developer.android.com/reference/android/app/IntentService.html.

Implement onHandleIntent(Intent intent) which will be called each time you start service with the startService(intent). You can pass your data to service through this intent.



回答2:

If you are trying to send a string or String-array from one Activity to another this can be done in the Intent.

In ClassA:

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

In ClassB:

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