((Button)) inside the service is not working

I'm trying to create a button that allows me to record audio through a service, I want the button to have the text: "Start Recording" . In the OnClick event OnClick I want the button text to change to: "Stop Recording" .

I had this code working when it was in the class, but now it doesn’t work in the service, however, since I want the sound recording to work as a service, I can’t get the button text to change. I am new to coding, so any help would be greatly appreciated!

My code is as follows:

Grade:

 public class Test extends AppCompatActivity { public void Record(View view) { Intent intent = new Intent(this, RecordService.class); startService(intent); } public void Play(View view) { Intent intent = new Intent(this, RecordService.class); stopService(intent); } } 

Services:

 import android.app.Service; import android.content.Intent; import android.media.MediaRecorder; import android.os.Environment; import android.os.IBinder; import android.widget.Button; import android.view.View; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class RecordService extends Service { MediaRecorder mRecorder; public static String audioFilePath; public boolean isRecording = false; public RecordService() { } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } public void onCreate () { if(mRecorder == null){ SimpleDateFormat s = new SimpleDateFormat("ddMMyyyy_hhmmss"); String format = s.format(new Date()); audioFilePath = Environment.getExternalStorageDirectory(). getAbsolutePath() + "/" + format + ".3gpp"; mRecorder = new MediaRecorder(); mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); mRecorder.setOutputFile(audioFilePath); mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); } if (isRecording) { try{ stopRecording(); isRecording = false; ((Button)view).setText("Start Recording"); }catch(Exception e){ e.printStackTrace(); } } else { try{ startRecording(); isRecording = true; ((Button)view).setText("Stop Recording"); }catch(Exception e){ e.printStackTrace(); } } } public void startRecording() throws IllegalStateException, IOException{ mRecorder.prepare(); mRecorder.start(); } public void stopRecording() throws IllegalStateException, IOException{ mRecorder.stop(); mRecorder.release(); } public void onStartCommand() { SimpleDateFormat s = new SimpleDateFormat("ddMMyyyy_hhmmss"); String format = s.format(new Date()); audioFilePath = Environment.getExternalStorageDirectory(). getAbsolutePath() + "/" + format + ".3gpp"; mRecorder = new MediaRecorder(); mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); mRecorder.setOutputFile(audioFilePath); mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); try { mRecorder.prepare(); } catch (IOException e) { e.printStackTrace(); } mRecorder.start(); } public void onDestroy() { super.onDestroy(); mRecorder.stop(); mRecorder.release(); } } 

Activity:

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="kyr.com.knowyourrights.Test"> <TextView android:text="@string/hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:text="Record" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/RecordButton" android:layout_alignParentTop="true" android:onClick="Record"> </Button> </RelativeLayout> 
+6
source share
6 answers

You want to call a button in a service, try using BroadcastReceiver

+1
source

This really cannot work here, since your ((button)) is not created in your onCreate ().

I suggest you call the function inside the Activity from the service that does what you want to do (change the text here). You can achieve this using BroadcastReceiver.

To do this, you can do the following:

Inside your activity:

 @Override public void onResume() { super.onResume(); // Register mMessageReceiver to receive messages. LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("change-text")); } // handler for received Intents for the "change-text" event private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Extract data included in the Intent String message = intent.getStringExtra("message"); button.setText(message); //Assuming you have instantiate properly your button inside your onCreate() } }; @Override protected void onPause() { // Unregister since the activity is not visible LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver); super.onPause(); } 

Inside your service:

 // Send an Intent with an action named "change-text". private void sendMessage(boolean startRecording) { Intent intent = new Intent("change-text"); // add data if (startRecording) intent.putExtra("message", "Start Recording"); else intent.putExtra("message","Stop Recording"); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } 

To change the text button from your service, you just need to call the sendMessage function with a parameter of true or false as a parameter, depending on what you want to do!

You can see the source of the code that I adapted to your situation here: http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html#ownreceiver_localbroadcastmanager

+1
source

Something like this will work

 if (isRecording) { try { stopRecording(); isRecording = false; yourcontext.runOnUiThread(new Runnable() { public void run() { ((Button) view).setText("Start Recording"); } }); } catch (Exception e) { e.printStackTrace(); } } else { try { startRecording(); isRecording = true; yourcontext.runOnUiThread(new Runnable() { public void run() { ((Button) view).setText("Stop Recording"); } }); } catch (Exception e) { e.printStackTrace(); } } 
0
source

It may be better to change the text in action, it may be more in line with the spirit of service. You should take a look at this topic: Example: Communication between an Activity and a Service Using Messages

In my opinion, creating a handler in Messenger is a very useful and effective way to create a communication bridge between your service and activity. Thus, you will most likely create status tags that represent the current state of your Service, for example, in your case:

 Message message = new Message(); message.setData(b); // bundle containing extra data if you need it message.what = MSG_RECORD_STOP; mActivity.send(message); 

Then in your activity, as soon as you get a callback from your Messenger, you can just do something like:

 (TextView) mRecordButton =(TextView)rootView.findViewById(R.id.RecordButton); mRecordButton.setText("Stop Recording"); 
0
source

Why do you want to change the button text in the service? Perhaps this is what you really need. Public class Test extends AppCompatActivity {

 public void Record(View view) { Intent intent = new Intent(this, RecordService.class); startService(intent); yourButton.setText("Stop Recording"); } public void Play(View view) { Intent intent = new Intent(this, RecordService.class); stopService(intent); yourButton.setText("Start Recording"); } 

}

0
source

Declare your button as static in your activity, for example.

 public static Button recordButton; public void onCreate(Bundle savedInstanceState) { .... recordButton =(Button) findViewById(R.id.RecordButton); .... } 

then do something similar in your service where you want

 WeakReference<Button> recordButton = new WeakReference<Button>(YourActivity.recordButton); recordButton.setText("Start Recording"); 
0
source

All Articles