Android 使用 Intent 将数据从 Activity 传递到 Service
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3293243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass data from Activity to Service using an Intent
提问by GobiasKoffi
How do I get data within an Android Service
that was passed from an invoking Activity
?
如何在 AndroidService
中获取从调用传递的数据Activity
?
采纳答案by Pentium10
First Context (can be Activity/Service etc)
第一个上下文(可以是活动/服务等)
For Service, you need to override onStartCommand there you have direct access to intent
:
对于服务,您需要覆盖 onStartCommand 那里您可以直接访问intent
:
Override
public int onStartCommand(Intent intent, int flags, int startId) {
You have a few options:
您有几个选择:
1) Use the Bundlefrom the Intent:
Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);
2) Create a new Bundle
2) 创建一个新的 Bundle
Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.extras.putString(key, value);
mIntent.putExtras(mBundle);
3) Use the putExtra()shortcut method of the Intent
3)使用Intent的putExtra()快捷方法
Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);
New Context (can be Activity/Service etc)
新上下文(可以是活动/服务等)
Intent myIntent = getIntent(); // this getter is just for example purpose, can differ
if (myIntent !=null && myIntent.getExtras()!=null)
String value = myIntent.getExtras().getString(key);
}
NOTE:Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.
注意:Bundle 对所有原始类型、Parcelables 和 Serializable 都有“get”和“put”方法。我只是将字符串用于演示目的。
回答by user_CC
For a precise answer to this question on "How to send data via intent from an Activity to Service", Is that you have to override the onStartCommand()
method which is where you receive the intent object:
对于“如何通过意图从活动到服务发送数据”这个问题的准确答案,您是否必须覆盖onStartCommand()
接收意图对象的方法:
When you create a Service
you should override the onStartCommand()
method so if you closely look at the signature below, this is where you receive the intent
object which is passed to it:
当您创建 a 时,Service
您应该覆盖该onStartCommand()
方法,因此如果您仔细查看下面的签名,您会在此处接收intent
传递给它的对象:
public int onStartCommand(Intent intent, int flags, int startId)
So from an activity you will create the intent object to start service and then you place your data inside the intent object for example you want to pass a UserID
from Activity
to Service
:
因此,从活动中,您将创建意图对象以启动服务,然后将数据放置在意图对象中,例如您希望将UserID
from传递Activity
给Service
:
Intent serviceIntent = new Intent(YourService.class.getName())
serviceIntent.putExtra("UserID", "123456");
context.startService(serviceIntent);
When the service is started its onStartCommand()
method will be called so in this method you can retrieve the value (UserID) from the intent object for example
当服务启动时,它的onStartCommand()
方法将被调用,因此在此方法中,您可以从意图对象中检索值(用户 ID),例如
public int onStartCommand (Intent intent, int flags, int startId) {
String userID = intent.getStringExtra("UserID");
return START_STICKY;
}
Note: the above answer specifies to get an Intent with getIntent()
method which is not correct in context of a service
注意:上面的答案指定使用getIntent()
在服务上下文中不正确的方法获取 Intent
回答by Martin Pfeffer
If you bind your service, you will get the Extra in onBind(Intent intent)
.
如果你绑定你的服务,你会在onBind(Intent intent)
.
Activity:
活动:
Intent intent = new Intent(this, LocationService.class);
intent.putExtra("tour_name", mTourName);
bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
Service:
服务:
@Override
public IBinder onBind(Intent intent) {
mTourName = intent.getStringExtra("tour_name");
return mBinder;
}
回答by Carlos Gómez
Another posibility is using intent.getAction:
另一种可能性是使用 intent.getAction:
In Service:
服务中:
public class SampleService inherits Service{
static final String ACTION_START = "com.yourcompany.yourapp.SampleService.ACTION_START";
static final String ACTION_DO_SOMETHING_1 = "com.yourcompany.yourapp.SampleService.DO_SOMETHING_1";
static final String ACTION_DO_SOMETHING_2 = "com.yourcompany.yourapp.SampleService.DO_SOMETHING_2";
static final String ACTION_STOP_SERVICE = "com.yourcompany.yourapp.SampleService.STOP_SERVICE";
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent.getAction();
//System.out.println("ACTION: "+action);
switch (action){
case ACTION_START:
startingService(intent.getIntExtra("valueStart",0));
break;
case ACTION_DO_SOMETHING_1:
int value1,value2;
value1=intent.getIntExtra("value1",0);
value2=intent.getIntExtra("value2",0);
doSomething1(value1,value2);
break;
case ACTION_DO_SOMETHING_2:
value1=intent.getIntExtra("value1",0);
value2=intent.getIntExtra("value2",0);
doSomething2(value1,value2);
break;
case ACTION_STOP_SERVICE:
stopService();
break;
}
return START_STICKY;
}
public void startingService(int value){
//calling when start
}
public void doSomething1(int value1, int value2){
//...
}
public void doSomething2(int value1, int value2){
//...
}
public void stopService(){
//...destroy/release objects
stopself();
}
}
In Activity:
在活动中:
public void startService(int value){
Intent myIntent = new Intent(SampleService.ACTION_START);
myIntent.putExtra("valueStart",value);
startService(myIntent);
}
public void serviceDoSomething1(int value1, int value2){
Intent myIntent = new Intent(SampleService.ACTION_DO_SOMETHING_1);
myIntent.putExtra("value1",value1);
myIntent.putExtra("value2",value2);
startService(myIntent);
}
public void serviceDoSomething2(int value1, int value2){
Intent myIntent = new Intent(SampleService.ACTION_DO_SOMETHING_2);
myIntent.putExtra("value1",value1);
myIntent.putExtra("value2",value2);
startService(myIntent);
}
public void endService(){
Intent myIntent = new Intent(SampleService.STOP_SERVICE);
startService(myIntent);
}
Finally, In Manifest file:
最后,在清单文件中:
<service android:name=".SampleService">
<intent-filter>
<action android:name="com.yourcompany.yourapp.SampleService.ACTION_START"/>
<action android:name="com.yourcompany.yourapp.SampleService.DO_SOMETHING_1"/>
<action android:name="com.yourcompany.yourapp.SampleService.DO_SOMETHING_2"/>
<action android:name="com.yourcompany.yourapp.SampleService.STOP_SERVICE"/>
</intent-filter>
</service>
回答by vishalknishad
Activity:
活动:
int number = 5;
Intent i = new Intent(this, MyService.class);
i.putExtra("MyNumber", number);
startService(i);
Service:
服务:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && intent.getExtras() != null){
int number = intent.getIntExtra("MyNumber", 0);
}
}
回答by Debasish Ghosh
This is a much better and secured way. Working like a charm!
这是一种更好且安全的方式。像魅力一样工作!
private void startFloatingWidgetService() {
startService(new Intent(MainActivity.this,FloatingWidgetService.class)
.setAction(FloatingWidgetService.ACTION_PLAY));
}
instead of :
代替 :
private void startFloatingWidgetService() {
startService(new Intent(FloatingWidgetService.ACTION_PLAY));
}
Because when you try 2nd one then you get an error saying : java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.floatingwidgetchathead_demo.SampleService.ACTION_START }
因为当您尝试第二个时,您会收到一条错误消息: java.lang.IllegalArgumentException:Service Intent must be explicit: Intent { act=com.floatingwidgetchathead_demo.SampleService.ACTION_START }
Then your Service be like this :
那么你的服务是这样的:
static final String ACTION_START = "com.floatingwidgetchathead_demo.SampleService.ACTION_START";
static final String ACTION_PLAY = "com.floatingwidgetchathead_demo.SampleService.ACTION_PLAY";
static final String ACTION_PAUSE = "com.floatingwidgetchathead_demo.SampleService.ACTION_PAUSE";
static final String ACTION_DESTROY = "com.yourcompany.yourapp.SampleService.ACTION_DESTROY";
@SuppressLint("LogConditional")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent.getAction();
//System.out.println("ACTION: "+action);
switch (action){
case ACTION_START:
Log.d(TAG, "onStartCommand: "+action);
break;
case ACTION_PLAY:
Log.d(TAG, "onStartCommand: "+action);
addRemoveView();
addFloatingWidgetView();
break;
case ACTION_PAUSE:
Log.d(TAG, "onStartCommand: "+action);
break;
case ACTION_DESTROY:
Log.d(TAG, "onStartCommand: "+action);
break;
}
return START_STICKY;
}
回答by Rohit Singh
Pass data from Activity to IntentService
将数据从 Activity 传递到 IntentService
This is how I pass data from Activity
to IntentService
.
这就是我从Activity
to传递数据的方式IntentService
。
One of my applicationhas this scenario.
我的一个应用程序有这种情况。
MusicActivity ------url(String)------> DownloadSongService
MusicActivity ------url(String)------> DownloadSongService
1) Send Data (Activity code)
1)发送数据(活动代码)
Intent intent = new Intent(MusicActivity.class, DownloadSongService.class);
String songUrl = "something";
intent.putExtra(YOUR_KEY_SONG_NAME, songUrl);
startService(intent);
2) Get data in Service (IntentService code)
You can access the intent in the onHandleIntent()
method
2)在Service中获取数据(IntentService代码)
可以在onHandleIntent()
方法中访问intent
public class DownloadSongService extends IntentService {
@Override
protected void onHandleIntent(@Nullable Intent intent) {
String songUrl = intent.getStringExtra("YOUR_KEY_SONG_NAME");
// Download File logic
}
}
回答by surya
Service: startservice can cause side affects,best way to use messenger and pass data.
服务:startservice 会引起副作用,最好的方法是使用 Messenger 和传递数据。
private CallBackHandler mServiceHandler= new CallBackHandler(this);
private Messenger mServiceMessenger=null;
//flag with which the activity sends the data to service
private static final int DO_SOMETHING=1;
private static class CallBackHandler extends android.os.Handler {
private final WeakReference<Service> mService;
public CallBackHandler(Service service) {
mService= new WeakReference<Service>(service);
}
public void handleMessage(Message msg) {
//Log.d("CallBackHandler","Msg::"+msg);
if(DO_SOMETHING==msg.arg1)
mSoftKeyService.get().dosomthing()
}
}
Activity:Get Messenger from Intent fill it pass data and pass the message back to service
活动:从 Intent 获取 Messenger 填充它传递数据并将消息传递回服务
private Messenger mServiceMessenger;
@Override
protected void onCreate(Bundle savedInstanceState) {
mServiceMessenger = (Messenger)extras.getParcelable("myHandler");
}
private void sendDatatoService(String data){
Intent serviceIntent= new
Intent(BaseActivity.this,Service.class);
Message msg = Message.obtain();
msg.obj =data;
msg.arg1=Service.DO_SOMETHING;
mServiceMessenger.send(msg);
}