开发者

How to pass a value in Services?

开发者 https://www.devze.com 2023-02-15 16:36 出处:网络
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 getInte

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 c开发者_C百科lass


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消