问题
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);
}
}
Here is my Service class:
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();
}
}
回答1:
I need to call
mainActivity.getSetVocabulary()
In such case you don't want to serialize anything (especially Activity
which is all kinds of wrong).
Instead, try binding Activity
to Service
. This will allow your Service
and Activity
to communicate. Please consult this question on how to call Activity
class method from Service
.
回答2:
You want to return data from your Service
to your Activity
. There are several ways to do this:
- 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()
.
来源:https://stackoverflow.com/questions/45594933/android-intent-getextras-getserializableconstants-codicemainactivity-is-nul