I'm new to Android developing and I would like to make an app that sends and receive text using bluetooth. I got everything regarding the sending text logically working, but when I try to test it in my phone, I can't see the interface.
Here's the Main Activity Code
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set; import java.util.UUID;
public class MainActivity extends ActionBarActivity {
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
EditText myTextbox;
TextView myLabel;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
Button sendButton = (Button) findViewById(R.id.send);
Button openButton = (Button) findViewById(R.id.open);
myTextbox = (EditText) findViewById(R.id.editText);
myLabel = (TextView) findViewById(R.id.textView);
openButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
findBT();
openBT();
} catch (IOException ex) {
}
}
});
// send data typed by the user to be printed
sendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
sendData();
} catch (IOException ex) {
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// This will find a bluetooth device
void findBT() {
try {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
myLabel.setText("No bluetooth adapter available");
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
// Salaxy S4 is the name of the bluetooth device
if (device.getName().equals("Galaxy S4")) {
mmDevice = device;
break;
}
}
}
myLabel.setText("Bluetooth Device Found");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// Tries to open a connection to the bluetooth device
void openBT() throws IOException {
try {
// Standard SerialPortService ID
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
myLabel.setText("Bluetooth Opened");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// After opening a connection to bluetooth device,
// we have to listen and check if a data were sent to be printed.
void beginListenForData() {
try {
final Handler handler = new Handler();
// This is the ASCII code for a newline character
final byte delimiter = 10;
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()
&& !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0,
encodedBytes, 0,
encodedBytes.length);
final String data = new String(
encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
myLabel.setText(data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* This will send data to be printed by the bluetooth
*/
void sendData() throws IOException {
try {
// the text typed by the user
String msg = myTextbox.getText().toString();
msg += "\n";
mmOutputStream.write(msg.getBytes());
// tell the user data were sent
myLabel.setText("Data Sent");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
and here's my Fragment_main
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res/com.example.bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="top"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.bt.MainActivity$PlaceholderFragment" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Text Here" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</LinearLayout>
<Button
android:id="#+id/open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/send"
android:layout_alignBottom="#+id/send"
android:layout_alignRight="#+id/linearLayout1"
android:text="Open" />
<Button
android:id="#+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout1"
android:layout_marginTop="15dp"
android:layout_toLeftOf="#+id/button1"
android:text="Send" />
<TextView
android:id="#+id/recievedText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/send"
android:layout_below="#+id/send"
android:layout_marginTop="20dp"
android:text="Received Text" />
<TextView
android:id="#+id/rtArea"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/recievedText"
android:layout_alignParentBottom="true"
android:layout_below="#+id/recievedText"
android:layout_marginTop="20dp"
android:text="Received Text Will be Displayed Here..." />
</RelativeLayout>
my Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bt"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<supports-screens android:anyDensity="true" />
<uses-permission android:name="android.permissions.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.bt.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
So I would like to know:
Why can't I see the interface and test my code?
How can I receive text inside the app itself?
Appreciate all your help guys.
One step at a time.
setContentView(R.layout.activity_main);
will set the content of the view and i am assuming its defined in your Fragment_main should be fragment_main as its a XML file. So if you change it to
setContentView(R.layout. fragment_main);
you should be able to see the user Interface.
Related
I've searched many tutorials on stackoverflow but can't understand anything and no one has a similar code as me.
I just want to send an "a" when i click the OFF button and "A" when i click the "ON" button. I used the OutputStream.write method but it is not working.
Here is my code:
jetControl.java
package com.example.btjetski;
import android.app.ProgressDialog;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.UUID;
public class jetControl extends AppCompatActivity {
Button buttonON1, buttonOFF1;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private final boolean isBtConnected = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jet_control);
Intent intent = getIntent();
address = intent.getStringExtra(Peripherique.EXTRA_ADDRESS); //recevoir l'adresse du périphérique BT
}
private void setOnClickListener() {
buttonON1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TurnOnJetski1();
}
});
buttonOFF1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TurnOffJetski1();
}
});
}
private void TurnOnJetski1() {
if (btSocket != null) {
try {
btSocket.getOutputStream().write("A".getBytes());
} catch (IOException e) {
Toast.makeText(this, "Erreur", Toast.LENGTH_LONG);
}
}
}
private void TurnOffJetski1() {
if (btSocket != null) {
try {
btSocket.getOutputStream().write("a".getBytes());
} catch (IOException e) {
Toast.makeText(this, "Erreur", Toast.LENGTH_LONG);
}
}
}
private void Disconnect() {
if (btSocket != null) {
try {
btSocket.close();
} catch (IOException e) {
Toast.makeText(this, "Erreur", Toast.LENGTH_LONG);
}
}
finish();
}
}
activity_jet_control.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".jetControl">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="4dp"
android:layout_marginTop="8dp"
android:text="Contrôle de JETSKI"
android:textSize="24dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="47dp"
android:layout_marginTop="95dp"
android:text="Jetski 1"
android:textSize="18sp" />
<Button
android:id="#+id/buttonON1"
android:layout_width="81dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp"
android:layout_marginTop="129dp"
android:backgroundTint="#12730C"
android:text="ON" />
<Button
android:id="#+id/buttonOFF1"
android:layout_width="77dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="86dp"
android:layout_marginTop="129dp"
android:backgroundTint="#FF0000"
android:text="OFF" />
</RelativeLayout>
I have an android app which is recording audio and outputting it withe the name audiorecorder to the local storage on the phone.
Now i would like store a .txt file as well in same directory.
I have tried several methods from stack overflow, the app doesn't complain but does not store the .txt as it should. I can't figure out why.
The methods of interest is: CreateTxt and generateNote. These are the ones that doesn't do what they are supposed to.
These methods are used within the startR.setOnClickListener method.
Can anybody see why? Thank you in advance.
package xxxx;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import static android.provider.AlarmClock.EXTRA_MESSAGE;
public class DataCollectionActivity extends AppCompatActivity {
private MediaPlayer mediaPLayer;
private MediaRecorder recorder;
private String OUTPUT_FILE;
public Button GoToUserAcc;
public Button GoToLogin;
public Button GoToTest;
// Permission Variables
private static final String LOG_TAG = "AudioRecordTest";
private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
private static String mFileName = null;
private boolean permissionToRecordAccepted = false;
private String [] permissions =
{Manifest.permission.RECORD_AUDIO,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.INTERNET};
private static final int
REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION = 200;
private boolean permissionToWriteExternalStoragedAccepted =
false;
private static final int REQUEST_INTERNET_PERMISSION = 200;
private boolean permissionToUseInternetAccepted = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_collec);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
Button startR = (Button) findViewById(R.id.Bstart);
Button stopR = (Button) findViewById(R.id.Bstop);
Button playRecording = (Button) findViewById(R.id.playBtn);
Button stopPlaying = (Button) findViewById(R.id.stopBtn);
final TextView statusTV;
statusTV = (TextView) findViewById(R.id.tStatus);
OUTPUT_FILE= Environment.getExternalStorageDirectory().
getAbsolutePath()+"/audiorecorder.3gpp";
ActivityCompat.requestPermissions(this, permissions,
REQUEST_RECORD_AUDIO_PERMISSION);
/*------START recording BUTTON------*/
startR.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
final TextView stv=statusTV;
try {
beginRecording();
stv.setText("Recording");
//CreateTxt();
generateNote("MLdata", "sBody");
stv.setText("Created txt");
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
stv.setText("Error");
}
}
});
/*------STOP BUTTON------*/
stopR.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
final TextView stv=statusTV;
try {
stopRecording();
stv.setText("Stopped");
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
statusTV.setText("Error");
Log.d("here","dd",e);
}
}
});
}
private void stopPlayback() throws Exception{
if(mediaPLayer != null)
mediaPLayer.stop();
}
private void playRecording() throws IOException {
ditchMediaPLayer();
mediaPLayer = new MediaPlayer();
mediaPLayer.setDataSource(OUTPUT_FILE);
mediaPLayer.prepare();
mediaPLayer.start();
}
private void ditchMediaPLayer() {
if (mediaPLayer != null) {
try{
mediaPLayer.release();
} catch(Exception e) {
e.printStackTrace();
}
}
}
private void stopRecording() {
if(recorder != null)
recorder.stop();
}
private void beginRecording() throws Exception{
ditchMediaRecorder();
File outFile = new File(OUTPUT_FILE);
//DataCollectionActivity dca = new DataCollectionActivity();
//dca.CreateTxt();
if (outFile.exists()) {
outFile.delete();
}
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.
OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(OUTPUT_FILE);
/*API constraints
Container WAV
Encoding PCM
Rate 16K
Sample Format 16 bit OK
Channels Mono OK
*/
recorder.setAudioSamplingRate(16);
//channel 1 equals mono, 2 eqals stereo
recorder.setAudioChannels(1);
recorder.prepare();
recorder.start();
}
private void ditchMediaRecorder() {
if(recorder != null)
recorder.release();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
if (item.getItemId() == R.id.action_setting){
Toast.makeText(DataCollectionActivity.this, "You have
clicked on setting action menu", Toast.LENGTH_SHORT).show();
}
if (item.getItemId() == R.id.action_about_us){
Toast.makeText(DataCollectionActivity.this, "You have
clicked on about us action menu", Toast.LENGTH_SHORT).show();
goToUserAccount();
}
return super.onOptionsItemSelected(item);
}
// Requesting permission to RECORD_AUDIO
//fra android.com
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull
String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
switch (requestCode){
case REQUEST_RECORD_AUDIO_PERMISSION:
permissionToRecordAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
break;
}
if (!permissionToRecordAccepted ) finish();
//---ny permission ---
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
switch (requestCode){
case REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION:
permissionToWriteExternalStoragedAccepted =
grantResults[0] == PackageManager.PERMISSION_GRANTED;
break;
}
if (!permissionToRecordAccepted ) finish();
//---ny permission ---
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
switch (requestCode){
case REQUEST_INTERNET_PERMISSION:
permissionToUseInternetAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
break;
}
if (!permissionToRecordAccepted ) finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mMenuInflater = getMenuInflater();
mMenuInflater.inflate(R.menu.menu_main, menu);
return true;
}
/** Opens up new activity */
//Vedrører tollbaren som ligenu ikke bliver brugt /virker ikke.
public void goToUserAccount() {
Intent intent = new Intent(this, UserAccountActivity.class);
EditText editText = (EditText)
findViewById(R.id.action_about_us);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
//Metode som laver en writer.
public void CreateTxt() throws IOException {
//concerning txt file
int id = 0;
String typeId = "S";
EditText db = (EditText) findViewById(R.id.dbNoiseText);
String dbString = db.getText().toString();
EditText numPar = (EditText)
findViewById(R.id.participatorsText);
String npar = numPar.getText().toString();
EditText conversationBool = (EditText)
findViewById(R.id.CoverationText);
String cBool = conversationBool.getText().toString();
File f = new File(Environment.getExternalStorageDirectory().
getAbsolutePath()+"dataForML.txt");
try {
System.out.print("enters try in createtxt");
PrintWriter writer = new PrintWriter(f, "UTF-8");
writer.println(dbString + ", ");
writer.println(npar + ", ");
writer.println(cBool + ", ");
writer.println(typeId + id + ", ");
writer.println(Environment.getExternalStorageDirectory().
getAbsolutePath()+"/dataForML.txt");
//Her skal den skrive binary. Metoden ligger i asrRequest
writer.println("Path to Acceleroeter CSV file ");
writer.println("\n");
writer.println();
writer.close();
id++;
} catch (IOException e) {
e.printStackTrace();
}
}
//OUTPUT_FILE= Environment.getExternalStorageDirectory().
getAbsolutePath()+"/audiorecorder.3gpp";
//generateNoteOnSD("MLdata", "sBody");
public void generateNote(String sFileName, String sBody) {
try {
File root = new
File(Environment.getExternalStorageDirectory().
getAbsolutePath(), "NotesML");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
//Toast.makeText(context, "Saved",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void thirdTry(){
String FILENAME = "hello_file";
String string = "hello world!";
try{
FileOutputStream fos = openFileOutput(FILENAME,
Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
layout xml comes here
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:orientation="vertical"
android:weightSum="1">
<EditText
android:id="#+id/dbNoiseText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="db noise"
android:inputType="textPersonName"
android:textAlignment="center"
android:textSize="24sp" />
<EditText
android:id="#+id/participatorsText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="# participators"
android:inputType="textPersonName"
android:textAlignment="center"
android:textSize="24sp" />
<EditText
android:id="#+id/CoverationText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Conversation? Y/N"
android:inputType="textPersonName"
android:textAlignment="center" />
<Button
android:id="#+id/Bstart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:text="Start Recording" />
<Button
android:id="#+id/Bstop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:text="Stop recording" />
<TextView
android:id="#+id/tStatus"
android:layout_width="354dp"
android:layout_height="42dp"
android:text="status"
android:textAlignment="center"
android:textSize="24sp" />
</LinearLayout>
Manifest comes here
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="dk.itu.percomp17.jumanji">
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"
/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category
android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".UserAccountActivity" />
<activity android:name=".RegisterActivity" />
<activity android:name=".LoginActivity"/>
<activity android:name=".DataCollectionActivity"/>
<activity android:name=".CallingjsActivity">
</activity>
</application>
</manifest>
I found out. Following method solved it.
// Once a file has been created, use this method to publicize
//the file as it can be seen !!
// But be sure to add "Context context;" outside of the method.
// Plus, remember to add "context = getApplicationContext ();" in the
//onCreate () method.
public void scanFile(String path) {
MediaScannerConnection.scanFile(context,
new String[] { path }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("TAG", "Finished scanning " + path);
}
});
}
I have made an android app using android studio were through bluetooth module (hc05) and arduino I'm sending sensor data to the app. I have added a torch application in it and willing to control it's on and off according to the range set for the value that gets stored in amount variable.
I had convert the string value of DATA into integer and stored it in amount variable. For this conversion I used:
amount = Integer.parseInt(DATA);
The torch on and off button is through Image button.
Java code:
package com.example.sugandhabansal.bluetooth_torch;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class bluetooth_torch_Activity extends Activity
{
TextView myLabel,mydata,myvalue;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
private CameraManager mCameraManager;
private String mCameraId;
private ImageButton mTorchOnOffButton;
private Boolean isTorchOn;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.d("bluetooth_torch", "onCreate()");
setContentView(R.layout.activity_bluetooth_torch_);
Button openButton = (Button)findViewById(R.id.open);
Button closeButton = (Button)findViewById(R.id.close);
myLabel = (TextView)findViewById(R.id.label);
myvalue = (TextView)findViewById(R.id.value);
mydata = (TextView)findViewById(R.id.data);
//Open Button
openButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
findBT();
openBT();
}
catch (IOException ex) { }
}
});
//Close button
closeButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
closeBT();
}
catch (IOException ex) { }
}
});
mTorchOnOffButton = (ImageButton) findViewById(R.id.button_on_off);
isTorchOn = false;
Boolean isFlashAvailable = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!isFlashAvailable) {
AlertDialog alert = new AlertDialog.Builder(bluetooth_torch_Activity.this)
.create();
alert.setTitle("Error !!");
alert.setMessage("Your device doesn't support flash light!");
alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish();
System.exit(0);
}
});
alert.show();
return;
}
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
mCameraId = mCameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
mTorchOnOffButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (isTorchOn) {
turnOffFlashLight();
isTorchOn = false;
} else {
turnOnFlashLight();
isTorchOn = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
void findBT()
{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null)
{
myLabel.setText("No bluetooth adapter available");
}
if(!mBluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals("HC-05"))
{
mmDevice = device;
break;
}
}
}
myLabel.setText("Bluetooth Device Found");
}
void openBT() throws IOException
{
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
myLabel.setText("Bluetooth Connected");
}
void beginListenForData()
{
final Handler handler = new Handler();
final byte delimiter = 35; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String DATA = new String(encodedBytes, "US-ASCII");
Log.d("SKY",DATA);
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
mydata.setText(DATA);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
void closeBT() throws IOException
{
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText("Bluetooth Closed");
}
public void turnOnFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, true);
mTorchOnOffButton.setImageResource(R.drawable.on);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void turnOffFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, false);
mTorchOnOffButton.setImageResource(R.drawable.off);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onStop() {
super.onStop();
if(isTorchOn){
turnOffFlashLight();
}
}
#Override
protected void onPause() {
super.onPause();
if(isTorchOn){
turnOffFlashLight();
}
}
#Override
protected void onResume() {
super.onResume();
if(isTorchOn){
turnOnFlashLight();
}
}
}
Manifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sugandhabansal.bluetooth_torch">
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.flash" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name="bluetooth_torch_Activity"
android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
layout design xml code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Bluetooth Connection"
android:layout_below="#+id/open"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:text="Open"
android:layout_above="#+id/value"
android:layout_alignParentEnd="true" />
<Button
android:id="#+id/close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Value: "
android:id="#+id/value"
android:layout_marginTop="86dp"
android:layout_below="#+id/close" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="data"
android:id="#+id/data"
android:layout_alignTop="#+id/value"
android:layout_toEndOf="#+id/value" />
<ImageButton
android:layout_gravity="center"
android:id="#+id/button_on_off"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000"
android:src="#drawable/off"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="45dp" />
</RelativeLayout>
I am trying to create a simple record and play audio application for android using MediaRecorder and MediaPlayer when i try to stop recording i get in the logcat the following error E/MediaRecorder﹕ stop called in an invalid state: 4 i am testing on a moto g 2013 16 gb memory version 5.1
Main activity
package com.example.sebastin.myapplication;
import android.content.DialogInterface;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.GpsStatus;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilterWriter;
import java.io.IOException;
public class MainBina extends AppCompatActivity {
TextView texto;
Button boton ,boton2, boton3, boton4;
MediaPlayer Play;
MediaRecorder Record;
String grabacion;
String filePath;
String grabarState;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_bina);
filePath = Environment.getExternalStorageDirectory()+ "/audiorecordtest.3gp";
texto = (TextView) findViewById(R.id.textView);
//boton.setText("Grabar");
boton = (Button) findViewById(R.id.button);
boton2 = (Button) findViewById(R.id.button2);
boton3 = (Button) findViewById(R.id.button3);
texto.setText(boton.getText().toString());
boton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch ( boton.getText().toString())
{
case "grabar":
try {
startRecord();
} catch (Exception e) {
e.printStackTrace();
}
boton.setText("grabando");
break;
case "grabando":
try {
stopRecord();
} catch (Exception e) {
e.printStackTrace();
}
boton.setText("Grabar");
break;
}
}
});
boton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlay();
}
});
boton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
startPlay();
} catch (Exception e) {
e.printStackTrace();
}
}
});}
public void startRecord ()throws Exception{
if (Record!=null)
{
Record.release();
}
File fileOut = new File(filePath);
if (fileOut!=null)
{
fileOut.delete();
}
String fileName = "bina1.3gpp";
FileOutputStream fileOutputStream = openFileOutput(fileName, MODE_PRIVATE);
String filePathh = fileOutputStream.toString();
texto.setText(filePath);
Record = new MediaRecorder();
Record.setAudioSource(MediaRecorder.AudioSource.MIC);
Record.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
Record.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
Record.setOutputFile(filePath);
fileOutputStream.close();
Record.prepare();
Record.start();
}
public void stopRecord () {
Record.stop();
Record.reset();
Record.release();
Record = null;
}
public void startPlay ()throws Exception {
Play = new MediaPlayer();
Play.setDataSource(filePath);
Play.prepare();
Play.start();
Play.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer Play) {
Play.release();
}
});
}
public void stopPlay ()
{
if (Play != null) {
Play.stop();
Play.release();
Play = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main_bina, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
XML
<LinearLayout 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=".MainBina"
android:id="#+id/linear"
android:orientation="vertical">
<TextView android:text="#string/saludo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:id="#+id/textView"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Grabar"
android:id="#+id/button"
android:layout_marginTop="35dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Reproducir"
android:id="#+id/button2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Parar"
android:id="#+id/button3" />
</LinearLayout>
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sebastin.myapplication" >
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.write_external_storage" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainBina"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Are you sure it started correctly? Take a look at your logcat for other errors/exceptions.
Your permission for writing to external storage looks wrong, it should be (with the last part capitalized):
android.permission.WRITE_EXTERNAL_STORAGE
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 7 years ago.
i am trying to develop an android app which will comunicate with other devices using wifi, when i run my code, it gives me networkOnMainThread exception. Dont understand what is wrong with my code.
Here is main class Code.
package com.example.sarwa.wifimessage;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText textOut;
TextView textIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("192.168.1.3", 8888);
//192.168.56.1
// 192.168.1.2
//192.168.1.101
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Error1 = " + e, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Error2 = " + e, Toast.LENGTH_SHORT).show();
}
catch(Exception ex){
Toast.makeText(getBaseContext(), "Error0 = " + ex, Toast.LENGTH_SHORT).show();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Error3 = " + e, Toast.LENGTH_SHORT).show();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Error4 = " + e, Toast.LENGTH_SHORT).show();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getBaseContext(), "Error5 = " + e, Toast.LENGTH_SHORT).show();
}
}
}
}};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is the menifest code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sarwa.wifimessage" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here is the XML code for main class
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello PASHA"
/>
<EditText
android:id="#+id/textout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/send"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send"
/>
<TextView
android:id="#+id/textin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
You should not make network calls on main thread. Use AsycTask or start a different thread for that