Android: intent.getExtras().getSerializable(Constants.codiceMainActivity) is null

北慕城南 提交于 2019-12-13 20:12:33

问题


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 your Service and using AIDL create a method on your Service that returns data.
  • Create a BroadcastReceiver in your Activity that listens for a specific Intent ACTION. In your Service, when you want to send data to the Activity,create an Intent with the appropriate ACTION, add the data as "extras", and call sendBroadcast().


来源:https://stackoverflow.com/questions/45594933/android-intent-getextras-getserializableconstants-codicemainactivity-is-nul

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!