Android:intent.getExtras().getSerializable(Constants.codiceMainActivity)为null [英] Android: intent.getExtras().getSerializable(Constants.codiceMainActivity) is null
本文介绍了Android:intent.getExtras().getSerializable(Constants.codiceMainActivity)为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从我的主要活动中启动服务,并通过Serializable传递一个对象.但是,当我在Service中获取对象并调用方法时,该对象为null,我不知道为什么. 这是我的MainActivity类:
I want to start a service from my main activity and pass an object with Serializable. However when I get the object in the Service and I call a method, it is null and I don't know why. Here is my MainActivity class:
public class MainActivity extends AppCompatActivity implements View.OnClickListener, Serializable
{
private transient SetVocabulary setVocabulary;
private transient Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVocabulary = new SetVocabulary();
findViewById(R.id.imageDizionario).setOnClickListener(this);
findViewById(R.id.imageGruppi).setOnClickListener(this);
findViewById(R.id.imageImpara).setOnClickListener(this);
Intent intentService = new Intent(MainActivity.this, ServiceChiusuraApp.class);
intentService.putExtra(Constants.codiceMainActivity,this);
Bundle bundleService = new Bundle();
bundleService.putSerializable(Constants.codiceMainActivity,this);
intentService.putExtras(bundleService);
startService(intentService);
}
public SetVocabulary getSetVocabulary()
{
return setVocabulary;
}
@Override
public void onClick(View v)
{
startActivity(intent);
}
}
这是我的服务班级:
public class ServiceChiusuraApp extends Service
{
MainActivity mainActivity;
@Override
public IBinder onBind(Intent intent)
{
mainActivity = (MainActivity) intent.getExtras().getSerializable(Constants.codiceMainActivity);
return null;
}
@Override
public void onTaskRemoved(Intent rootIntent)
{
super.onTaskRemoved(rootIntent);
SharedPreferences sharedPref = mainActivity.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putStringSet(Constants.codiceSetString,mainActivity.getSetVocabulary());
stopSelf();
}
}
推荐答案
您想将数据从Service
返回到Activity
.有几种方法可以做到这一点:
You want to return data from your Service
to your Activity
. There are several ways to do this:
- 将
Activity
绑定到Service
,并使用AIDL在Service
上创建一个返回数据的方法. - 在
Activity
中创建一个BroadcastReceiver
,以侦听特定的Intent
ACTION.在您的Service
中,当您要将数据发送到Activity
时,使用适当的ACTION创建一个Intent
,将数据添加为"extras",然后调用sendBroadcast()
.
- Bind your
Activity
to yourService
and using AIDL create a method on yourService
that returns data. - Create a
BroadcastReceiver
in yourActivity
that listens for a specificIntent
ACTION. In yourService
, when you want to send data to theActivity
,create anIntent
with the appropriate ACTION, add the data as "extras", and callsendBroadcast()
.
这篇关于Android:intent.getExtras().getSerializable(Constants.codiceMainActivity)为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文