简体   繁体   中英

How can I access methods from my Main Activity in my Settings activity?

I am currently developing a Voice Recorder app for Android. I am trying to access a few methods in my MainActivity from my Settings activity, in order to change some settings for my MediaRecorder .

I have the method below, which sets up the Audio Settings for the recording, in my MainActivity .

// set up all audio settings
private void setAudioSettings() {
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
    mediaRecorder.setAudioSamplingRate(44100);
    mediaRecorder.setAudioEncodingBitRate(96000);
    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.HE_AAC);
}

In my Settings activity, I have a standard preferences screen that I would like to show options to change the audio codec, sampling rate, etc. of the media recorder in MainActivity .

How can I access the setAudioSettings method from MainActivity here in order to do so?

If you need to see more code or screenshots, please let me know.

Make that method as static so you can call without creating the class object

public static void yourMethod(){
//Write your code here
}

And call your method like this way:

MainActivity.yourMethod();

The short answer is you should not use the functions of your one activity into another activity.

For your case, I would suggest you to have a singleton object or shared preference to store your data of settings screen. Then in onStart of MainActivity, read the singleton object or shared preference and call #setAudioSettings method accordingly.

在共享首选项中保存设置即值,然后从主活动中的首选项中获取。

You can make your method static by:

  public static void setAudioSettings() {
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
    mediaRecorder.setAudioSamplingRate(44100);
    mediaRecorder.setAudioEncodingBitRate(96000);
    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.HE_AAC);
}

But to do that mediaRecorder needs to be static also.

Later you can call this method from any activity by:

MainActivity.setAudioSettings();

You can learn more about static keyword for example here .

But, I am not sure that use of static method is the best solution for exactly your problem, maybe will be better to set SharedPreferences in your SettingActivity and later in onResume() of your MainActivity call setAudioSettings() method and get there values from SharedPreferences ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM