Android Arduino Bluetooth communication crash on starting - java

i have been trying to use bluetooth to comunicate between arduino and bluetooth
and there is no errors on build
tell me what is wrong
i had issues with IO Exception but it solved now ... maybe
the app just crashes when i try to run it on phone
help me i am not that good at java
package com.example.administrator.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import java.util.Set;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import android.os.ParcelUuid;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_ENABLE_BT = 1;
private Button onBtn, offBtn ,listBtn ,findBtn;
private TextView text;
private Button UpBtn ,DownBtn ,LeftBtn ,RightBtn;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
private OutputStream outputStream;
private InputStream inStream;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> bondedDevices = myBluetoothAdapter.getBondedDevices();
if (myBluetoothAdapter == null) {
onBtn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
UpBtn.setEnabled(false);
DownBtn.setEnabled(false);
LeftBtn.setEnabled(false);
RightBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(), "Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
if(bondedDevices.size() > 0 ){
BluetoothDevice[] devices = (BluetoothDevice[]) bondedDevices.toArray();
BluetoothDevice device = devices[0];
ParcelUuid[] uuids = device.getUuids();
try{
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket.connect();
outputStream = socket.getOutputStream();
inStream = socket.getInputStream();
} catch (IOException e){
}
}
//Movement
UpBtn = (Button) findViewById(R.id.Upbutton);
DownBtn = (Button) findViewById(R.id.Downbutton);
LeftBtn = (Button) findViewById(R.id.Leftbutton);
RightBtn = (Button) findViewById(R.id.Rightbutton);
UpBtn.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
try {
C(v, 8);
}
catch (IOException e ){
System.out.println("3 SEND FAILED");
}
}
});
DownBtn.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
try {
C(v, 2);
} catch (IOException e) {
System.out.println("2 SEND FAILED");
}
}
});
LeftBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
C(v, 4);
} catch (IOException e) {
System.out.println(" 4 SEND FAILED");
}
}
});
RightBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
try {
C(v, 6);
} catch (IOException e) {
System.out.println(" 6 SEND FAILED");
}
}
}
);
//.........................
//..................
//Normal Code
text = (TextView) findViewById(R.id.textView);
//text.setText ( "" + myBluetoothAdapter.getName());
onBtn = (Button) findViewById(R.id.Onbutton);
onBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button) findViewById(R.id.Offbutton);
offBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
listBtn = (Button) findViewById(R.id.Listbutton);
listBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button) findViewById(R.id.Pairedbutton);
findBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView) findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
}
}
public void on(View view) {
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(), "Bluetooth turned on",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == REQUEST_ENABLE_BT) {
if (myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view) {
// get paired devices
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for (BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
Toast.makeText(getApplicationContext(), "Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
} else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
public void off(View view) {
myBluetoothAdapter.disable();
text.setText("Status: Disconnected");
Toast.makeText(getApplicationContext(), "Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
public void C (View View , float H) throws IOException{
if(H == 8){
outputStream.write("8".toString().getBytes());
}
if(H == 2){
outputStream.write("2".toString().getBytes());
}
if(H == 4){
outputStream.write("4".toString().getBytes());
}
if(H == 6){
outputStream.write("6".toString().getBytes());
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
}
and here is the manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.administrator.myapplication" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Solved it , it just was a permission error
just added the bluetooth_admin permission and it worked !!
thanks HaMiD Sani for pointing that out .

It's pretty tough to point out the root of your problem without a log but this is the example https://goo.gl/d7YD92 (by google) that I followed a few months ago to make a robust bluetooth communication between android and arduino. Worked like a charge after a couple of hours of playing with it. One place I would also look is your manifest to make sure that you got all the necessary permissions.

Related

How to make BLE scan and MQTT publish work in background Android Studio Java

I want make some project where Android can scan nearby Beacon/BLE and send it using MQTT. But I want the service to work in the background if the service work in the foreground it will interrupt the scanning process when screen is off.
This is my code for scanning:
package com.example.mqtt_active;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import java.nio.charset.StandardCharsets;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private Button turnon, changeLayout;
MqttAndroidClient client;
private boolean state=false;
private BluetoothAdapter bluetoothAdapter;
public static final int REQUEST_ACCESS_COARSE_LOCATION = 1;
public static final int REQUEST_ENABLE_BLUETOOTH = 11;
public static String mqtt_server,mqtt_port,mqtt_id;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
Log.d("Logger", "On Create Android");
turnon = findViewById(R.id.turnon);
changeLayout = findViewById(R.id.mqttSet);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
textView = findViewById(R.id.textView4);
textView.setText("id "+mqtt_id+" port "+mqtt_port+" server "+mqtt_server);
client = new MqttAndroidClient(this.getApplicationContext(), "tcp://"+mqtt_server+":"+mqtt_port,mqtt_id);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
stateCheck();
Log.d("Logger", "State Check");
handler.postDelayed(this, 1000);
}
}, 1000);
// final Handler handlerStop = new Handler();
// handlerStop.postDelayed(new Runnable() {
// #Override
// public void run() {
// bluetoothAdapter.cancelDiscovery();
// Log.d("Logger", "Cancel Dsicovery");
// handlerStop.postDelayed(this, 2000);
// }
// }, 2000);
turnon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!state){
turnon.setText("Turn Off");
Log.d("Logger", "Turn On State");
// if (bluetoothAdapter!=null & bluetoothAdapter.isEnabled()) {
// if(checkCoarsePermission()){
// bluetoothAdapter.startDiscovery();
// }
// }
if(mqtt_server!=null||mqtt_id!=null||mqtt_port!=null){
try {
Log.d("Logger", "Try ");
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d("Logger", "Connect MQTT");
Toast.makeText(MainActivity.this,"connected!!",Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d("Logger", "Connect Failed");
Toast.makeText(MainActivity.this,"connection failed!!",Toast.LENGTH_LONG).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
Log.d("Logger", "error"+e);
}}
state = true;
}else{
turnon.setText("Turn On");
state = false;
// bluetoothAdapter.cancelDiscovery();
}
}
});
changeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,MqttActivity.class));
}
});
}
public void stateCheck(){
if (state){
if (bluetoothAdapter!=null & bluetoothAdapter.isEnabled()) {
if(checkCoarsePermission()){
Log.d("Logger", "Discover");
bluetoothAdapter.startDiscovery();
}
}
}
// else {
// Log.d("Logger", "Cancel");
// bluetoothAdapter.cancelDiscovery();
// }
}
private boolean checkCoarsePermission(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_ACCESS_COARSE_LOCATION);
return false;
}else {
return true;
}
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(devicesFoundReceiver);
}
private final BroadcastReceiver devicesFoundReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action= intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
String RSSI = String.valueOf(rssi);
Toast.makeText(context.getApplicationContext(),"rssi "+RSSI+" "+device.getAddress(),Toast.LENGTH_SHORT).show();
Log.d("Logger", "Recive data "+device.getAddress());
if(mqtt_server!=null||mqtt_id!=null||mqtt_port!=null){
try {
Log.d("Logger", "Sending data");
String payload = "rssi:"+RSSI+"mac:"+device.getAddress();
client.publish("test",payload.getBytes(),0,false);
} catch ( MqttException e) {
e.printStackTrace();
Log.d("Logger", "Error Sending "+e);
}}
}else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
}else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
}
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_ACCESS_COARSE_LOCATION:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"ALLOWED", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"Forbidden",Toast.LENGTH_SHORT).show();
} break;
}
}
}
App Flow:
Insert MQTT server, port, id, topic.
Turn on the proccess.
Android scan BLE/Beacon
Android sending MAC/RSSI to MQTT
I hope someone can help to guide me, on how to make the application run in the background?
I'm a beginner, and I don't understand how to implement background service in my application. Please help me!
You need to implement a foreground service that will handle your ble scanning and MQTT logic.
See this article with an overview of how to do it. Depending on your build/target SDK, the implementation will vary.

Android Java app fails to send selected file/data via Bluetooth

My current android app can turn on Bluetooth, make itself discoverable, list paired devices, and select a file from the device ( ie an image). However when I attempted to hit "send" the app seems to crash with an error. Not sure if it's refusing to send, or if it's not actually obtaining the file (yesterday I had a problem where it refused to send the selected, saying for me to select a file repeatedly. I will post the crash results and my mainActivity code. If anyone suggestions or ideas, please let me know.
Error: Debugging device
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bluetooth_demoproject, PID: 17593
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=300, data=null} to activity {com.example.bluetooth_demoproject/com.example.bluetooth_demoproject.MainActivity}: android.os.FileUriExposedException: file:///storage/emulated/0/Pictures/Screenshots/Screenshot_20161013-215137.png exposed beyond app through ClipData.Item.getUri()
at android.app.ActivityThread.deliverResults(ActivityThread.java:4107)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4150)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1517)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6120)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: android.os.FileUriExposedException: file:///storage/emulated/0/Pictures/Screenshots/Screenshot_20161013-215137.png exposed beyond app through ClipData.Item.getUri()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1799)
at android.net.Uri.checkFileUriExposed(Uri.java:2346)
at android.content.ClipData.prepareToLeaveProcess(ClipData.java:832)
at android.content.Intent.prepareToLeaveProcess(Intent.java:8909)
at android.content.Intent.prepareToLeaveProcess(Intent.java:8894)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1517)
at android.app.Activity.startActivityForResult(Activity.java:4224)
at android.app.Activity.startActivityForResult(Activity.java:4183)
at android.app.Activity.startActivity(Activity.java:4507)
at android.app.Activity.startActivity(Activity.java:4475)
at com.example.bluetooth_demoproject.MainActivity.onActivityResult(MainActivity.java:350)
at android.app.Activity.dispatchActivityResult(Activity.java:6917)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4103)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4150) 
at android.app.ActivityThread.-wrap20(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1517) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6120) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Disconnected from the target VM, address: 'localhost:8601', transport: 'socket'
Here is my MainActivity
package com.example.bluetooth_demoproject;
import android.app.Activity;
import android.app.Dialog;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Set;
import java.io.File;
import java.util.List;
import java.util.ArrayList;
public class MainActivity extends Activity {
// Creating objects -----------------------------
private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_BLU = 1;
// private static final int REQUEST_DISCOVER_BT_ = 1;
private static int CUSTOM_DIALOG_ID = 0;
ListView dialog_ListView;
TextView mBluetoothStatus, mPairedDevicesList, mTextFolder;
ImageView mBluetoothIcon;
Button mOnButton, mDiscoverableButton, mPairedDevices, mbuttonOpenDialog, msendBluetooth, mbuttonUp;
File root, fileroot, curFolder;
EditText dataPath;
private static final int DISCOVER_DURATION = 300;
private List<String> fileList = new ArrayList<String>();
// -------------------------------------------------------
BluetoothAdapter mBlueAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataPath =(EditText)findViewById(R.id.FilePath);
mTextFolder = findViewById(R.id.folder);
mBluetoothStatus = findViewById(R.id.BluetoothStatus);
mBluetoothIcon = findViewById(R.id.bluetoothIcon);
mOnButton = findViewById(R.id.onButton);
// mOffButton = findViewById(R.id.offButton);
mDiscoverableButton = findViewById(R.id.discoverableButton);
mPairedDevices = findViewById(R.id.pairedDevices);
mPairedDevicesList = findViewById(R.id.pairedDeviceList);
mbuttonOpenDialog = findViewById(R.id.opendailog);
msendBluetooth = findViewById(R.id.sendBluetooth);
mbuttonUp = findViewById(R.id.up);
mbuttonOpenDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dataPath.setText("");
showDialog(CUSTOM_DIALOG_ID);
}
});
root = new
File(Environment.getExternalStorageDirectory().getAbsolutePath());
curFolder = root;
msendBluetooth.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
sendViaBluetooth();
}
});
//adapter
mBlueAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBlueAdapter == null){
mBluetoothStatus.setText("Bluetooth is not available");
return;
}
else {
mBluetoothStatus.setText("Bluetooth is available");
}
//if Bluetooth isnt enabled, enable it
if (!mBlueAdapter.isEnabled()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//set image according to bluetooth Status
if (mBlueAdapter.isEnabled()) {
mBluetoothIcon.setImageResource(R.drawable.action_on);
}
else {
mBluetoothIcon.setImageResource(R.drawable.action_off);
}
//on button Click
mOnButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (!mBlueAdapter.isEnabled()) {
showToast("Turning Bluetooth on...");
// intent to on bluetooth
Intent intent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_ENABLE_BT);
}
else {
showToast("Bluetooth is already on");
}
}
});
//discover Bluetooth button
mDiscoverableButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (!mBlueAdapter.isDiscovering()) {
showToast("Making device discoverable");
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(intent, REQUEST_BLU);
}
}
});
// off button click
// mOffButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// if (mBlueAdapter.isEnabled()) {
// showToast("Turning Bluetooth off...");
// // intent to turn off bluetooth
// mBluetoothIcon.setImageResource(R.drawable.action_off);
// }
// else{
// showToast("Bluetooth is already off");
// }
//
// }
//});
//get paired device button click
mPairedDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBlueAdapter.isEnabled()) {
mPairedDevices.setText("Paired Devices");
Set<BluetoothDevice> devices = mBlueAdapter.getBondedDevices();
for (BluetoothDevice device : devices){
mPairedDevices.append("\nDevice: " + device.getName() + "," + device );
}
}
else {
//bluetooth is off and cant get paired devices
showToast("Turn on bluetooth to get paired devices");
}
}
});
}
// #Override
// protected void onPrepareDialog(int id, Dialog dialog) {
// super.onPrepareDialog(id, dialog);
// switch (id) {
// case CUSTOM_DIALOG_ID:
// ListDir(curFolder);
// break;
// }
// }
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
if (id == CUSTOM_DIALOG_ID) {
dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dailoglayout);
dialog.setTitle("Select Files");
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
mTextFolder = (TextView) dialog.findViewById(R.id.folder);
mbuttonUp = (Button) dialog.findViewById(R.id.up);
mbuttonUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListDir(curFolder.getParentFile());
}
});
dialog_ListView = (ListView) dialog.findViewById(R.id.dialoglist);
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
File selected = new File(fileList.get(position));
if (selected.isDirectory()) {
ListDir(selected);
}
else if (selected.isFile()) {
getSelectedFile(selected);
}
else {
dismissDialog(CUSTOM_DIALOG_ID);
}
}
});
}
return dialog;
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
if (id == CUSTOM_DIALOG_ID) {
ListDir(curFolder);
}
}
public void getSelectedFile(File f) {
dataPath.setText(f.getAbsolutePath());
fileList.clear();
dismissDialog(CUSTOM_DIALOG_ID);
}
public void ListDir(File f) {
if (f.equals(root)) {
mbuttonUp.setEnabled(false);
}
else {
mbuttonUp.setEnabled(true);
}
curFolder = f;
mTextFolder.setText(f.getAbsolutePath());
dataPath.setText(f.getAbsolutePath());
File[] files = f.listFiles();
fileList.clear();
for (File file : files) {
fileList.add(file.getPath());
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fileList);
dialog_ListView.setAdapter(directoryList);
}
// exits to app --------------------------------
public void exit(View V) {
mBlueAdapter.disable();
Toast.makeText(this, "*** Now bluetooth is off...", Toast.LENGTH_LONG).show();
finish();
}
// send file via bluetooth ------------------------
public void sendViaBluetooth() {
if(!dataPath.equals(null)) {
if(mBlueAdapter == null) {
Toast.makeText(this, "Device doesnt support bluetooth", Toast.LENGTH_LONG).show();
}
else {
enableBluetooth();
}
}
else {
Toast.makeText(this, "please select a file", Toast.LENGTH_LONG).show();
}
}
public void enableBluetooth() {
showToast("Making device discoverable");
Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVER_DURATION);
startActivityForResult(discoveryIntent, REQUEST_BLU);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == DISCOVER_DURATION && requestCode == REQUEST_BLU) {
Intent i = new Intent();
i.setAction(Intent.ACTION_SEND);// STOPPED HERE-----------------------------------------------------------------
i.setType("*/*");
File file = new File(dataPath.getText().toString());
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
PackageManager pm = getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(i, 0);
if (list.size() > 0) {
String packageName = null;
String className = null;
boolean found = false;
for (ResolveInfo info : list) {
packageName = info.activityInfo.packageName;
if (packageName.equals("com.android.bluetooth")) {
className = info.activityInfo.name;
found = true;
break;
}
}
//CHECK BLUETOOTH available or not------------------------------------------------
if (!found) {
Toast.makeText(this, "Bluetooth not been found", Toast.LENGTH_LONG).show();
} else {
i.setClassName(packageName, className);
startActivity(i);
}
}
} else {
Toast.makeText(this, "Bluetooth is cancelled", Toast.LENGTH_LONG).show();
}
}
#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) {
// Toast.makeText(this, "**********************************\nDeveloper: www.santoshkumarsingh.com\n**********************************", Toast.LENGTH_LONG).show();
// return true;
// }
return super.onOptionsItemSelected(item);
}
//toast message function
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT) .show();
}
}
You have trouble with file exchange not with BLE.
Did you ever read Android FileUriExposedException?

I'm building a media player app, my application is getting a fatal exception

I don't know what to do now, I'm new to Android.
package com.example.macbookpro.myplayer;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
public class AudioPlayer extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener, MediaPlayer.OnCompletionListener {
ImageView btn_play;
Button btn_pause;
ImageView btn_next;
ImageView btn_prev;
ImageView btn_forward;
ImageView btn_backward;
TextView song_title;
int currentsongindex;
int seekForwardTime = 5000;
int seekBackwardTime = 5000;
private Utilities utilities;
Handler mHandler1=new Handler();
SeekBar song_progressbar;
final ArrayList<File> arrayList = new ArrayList<File>();
MediaPlayer mp = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_player);
btn_play = (ImageView) findViewById(R.id.btn_play);
btn_next = (ImageView) findViewById(R.id.btn_next);
btn_prev = (ImageView) findViewById(R.id.btn_prev);
btn_forward = (ImageView) findViewById(R.id.btn_forward);
btn_backward = (ImageView) findViewById(R.id.btn_backwrd);
song_title = (TextView) findViewById(R.id.tw);
song_progressbar=(SeekBar)findViewById(R.id.song_progressbar);
song_progressbar.setOnSeekBarChangeListener(this);
mp.setOnCompletionListener(this);
try {
PlaySongtwo(getIntent().getStringExtra("index"));
} catch (IOException e) {
e.printStackTrace();
}
final String[] sec = getIntent().getStringArrayExtra("index2");
currentsongindex = Integer.parseInt((getIntent().getStringExtra("positionofcurrentsong")));
utilities = new Utilities();
// Button for playing the song
btn_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
btn_play.setImageResource(R.drawable.button_play);
} else {
if (mp != null) {
mp.start();
btn_play.setImageResource(R.drawable.button_pause);
}
}
} else {
if (mp != null) {
mp.start();
btn_play.setImageResource(R.drawable.button_pause);
}
}
}
});
// Button for the next song in the list
btn_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Log.e("currenttt song is ",currentsongindex+"");
if(currentsongindex < (sec.length-1)){
int cc=currentsongindex+1;
Log.e("value in cc",cc+"");
try {
PlaySongtwo(sec[cc]);
} catch (IOException e) {
e.printStackTrace();
}
Log.e("next song number is ",cc +"");
currentsongindex = currentsongindex +1;
}else {
try {
PlaySongtwo(sec[0]);
} catch (IOException e) {
e.printStackTrace();
}
currentsongindex = 0;
}
}
});
//Button for the previous song in the list
btn_prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(currentsongindex > 0){
int prevsong= currentsongindex-1;
try {
PlaySongtwo(sec[prevsong]);
} catch (IOException e) {
e.printStackTrace();
}
Log.e("prev song",prevsong+"");
currentsongindex = prevsong;
}else {
try {
PlaySongtwo(String.valueOf((sec.length-1)));
} catch (IOException e) {
e.printStackTrace();
}
currentsongindex = sec.length-1;
}
}
});
//Button for fast-forwarding the song
btn_forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
int currentPosition = mp.getCurrentPosition();
if(currentPosition + seekForwardTime <= mp.getDuration() ){
mp.seekTo(currentPosition + seekForwardTime);
}else {
mp.seekTo(mp.getDuration());
}
}
});
//Button for fast-backwarding the song
btn_backward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
int currentPostion = mp.getCurrentPosition();
if(currentPostion - seekBackwardTime >= 0){
mp.seekTo(currentPostion - seekBackwardTime);
}else {
mp.seekTo(0);
}
}
});
}
private void PlaySongtwo(String path) throws IOException {
try {
String songname = path.substring(path.lastIndexOf("/") + 1);
song_title.setText(songname);
mp.reset();
Uri myUri = Uri.parse(path);
mp.setDataSource(AudioPlayer.this, myUri);
mp.prepare();
mp.start();
btn_play.setImageResource(R.drawable.button_pause);
song_progressbar.setProgress(0);
song_progressbar.setMax(100);
updateProgressBar1();
} catch (IOException e) {
e.printStackTrace();
}
}
private void updateProgressBar1() {
mHandler1.postDelayed(mUpdateTimeTask1,100);
}
private Runnable mUpdateTimeTask1=new Runnable() {
#Override
public void run() {
long totalDuration = mp.getDuration();
long currentDuration=mp.getCurrentPosition();
int progress=(int)(utilities.getProgresspercentage(currentDuration,totalDuration));
song_progressbar.setProgress(progress);
mHandler1.postDelayed(this,100);
}
};
#Override
protected void onDestroy ()
{
super.onDestroy();
mp.release();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
mHandler1.removeCallbacks(mUpdateTimeTask1);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler1.removeCallbacks(mUpdateTimeTask1);
int totalDuration=mp.getDuration();
int currentPosition=utilities.progressToTimer(seekBar.getProgress(),totalDuration);
mp.seekTo(currentPosition);
updateProgressBar1();
}
#Override
public void onCompletion(MediaPlayer mp1) {
enter code here
}
}
This is the error I'm facing.
11-06 13:30:03.935 1060-1060/com.example.macbookpro.myplayer E/MediaPlayer: Should have subtitle controller already set
11-06 13:30:04.031 1060-1060/com.example.macbookpro.myplayer E/MediaPlayer: Should have subtitle controller already set
11-06 13:30:22.260 1060-1060/com.example.macbookpro.myplayer D/AndroidRuntime: Shutting down VM
11-06 13:30:22.261 1060-1060/com.example.macbookpro.myplayer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.macbookpro.myplayer, PID: 1060
java.lang.IllegalStateException
at android.media.MediaPlayer.getDuration(Native Method)
at com.example.macbookpro.myplayer.AudioPlayer$6.run(AudioPlayer.java:220)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
My guess is that you are trying to getDuration before your MediaPlayer is ready to be used.
Make sure you're setting all controls that interact with the mediaplayer.

Flashlight won't turn on

Hi I followed I followed a tutorial here and wrote out the code, I tested it but the flashlight does not turn on and I cant figure out what's gone wrong.
I left out the parts where there was sound because I preferred there not to be any.
package net.netne.benpaterson35;
import android.app.*;
import android.os.*;
import android.hardware.*;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity
{
Button mainButton1;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainButton1 = (Button) findViewById(R.id.mainButton1);
hasFlash = getApplicationContext().getPackageManager().
hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Sorry");
alert.setMessage("This device doesn't have flash a flash light");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which){
finish();
}
});
alert.show();
return;
}
getCamera();
mainButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
if (isFlashOn){
turnOffFlash();}
else {
turnOnFlash();
}
};
});
}
private void getCamera(){
if (camera == null){
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Failed to open camera", e.getMessage());
}
}
}
private void turnOnFlash() {
if (!isFlashOn){
if (camera == null || params == null){
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
}
}
private void turnOffFlash() {
if (isFlashOn){
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
}
#Override
protected void onPause()
{
super.onPause();
turnOffFlash();
}
#Override
protected void onRestart()
{
super.onRestart();
}
#Override
protected void onResume()
{
super.onResume();
if(hasFlash)
turnOnFlash();
}
#Override
protected void onStart()
{
super.onStart();
getCamera();
}
#Override
protected void onStop()
{
super.onStop();
if (camera != null) {
camera.release();
camera = null;
}
}
}
Thanks for reading :)
if you are working on new device the code you followed wont work on newer devices i made it work on Lollipop device by following this code give it a try
mCam = Camera.open();
Camera.Parameters p = mCam.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCam.setParameters(p);
mPreviewTexture = new SurfaceTexture(0);
try {
mCam.setPreviewTexture(mPreviewTexture);
} catch (IOException ex) {
// Ignore
}
mCam.startPreview();
Did you add
<uses-permission android:name="android.permission.CAMERA" />
to your AndroidManifest?
Highly suspect you didn't add the permission.

In my application I need to record every incoming and outgoing call [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Below is the code of receiver class
package com.example.crecording;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IInterface;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class callReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
phoneListener phonestateListener = new phoneListener(context);
TelephonyManager telephony = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(phonestateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
class phoneListener extends PhoneStateListener{
private Context context;
phoneListener(Context c){
super();
context=c;
}
#Override
public void onCallStateChanged(int state, String incomingNumber) {
SharedPreferences preferences = context.getSharedPreferences("CallReceiver", Context.MODE_PRIVATE);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE :
Toast.makeText(context, state+"",Toast.LENGTH_SHORT).show();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
String phone_number = preferences.getString("phone_number",null);
Intent serv = new Intent(context,
cRecordingservice.class);
serv.putExtra("number", phone_number);
context.startService(serv);
Toast.makeText(context, state+"",Toast.LENGTH_SHORT).show();
break;
case TelephonyManager.CALL_STATE_RINGING :
SharedPreferences.Editor editor = preferences.edit();
editor.putString("phone_number", incomingNumber);
editor.commit();
Toast.makeText(context, state+""+incomingNumber,Toast.LENGTH_LONG).show();
break;
}
}
}
}
Below is the code for Call recording service
package com.example.crecording;
import java.io.File;
import java.io.IOException;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaRecorder;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class cRecordingservice extends Service {
MediaRecorder callrecorder;
Boolean recording;
MainActivity main=new MainActivity();
BroadcastReceiver myreceiver=new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
myphonestatelistener mpl=new myphonestatelistener(context);
TelephonyManager tm=(TelephonyManager)context.getSystemService(TELEPHONY_SERVICE);
tm.listen(mpl,PhoneStateListener.LISTEN_CALL_STATE);
}
class myphonestatelistener extends PhoneStateListener{
private Context context;
myphonestatelistener(Context c){
context=c;
}
#Override
public void onCallStateChanged(int state, String incomingNumber) {
// TODO Auto-generated method stub
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
if(recording){
stopRecording();
Toast.makeText(context, "stopped", Toast.LENGTH_SHORT).show();
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
if(!recording){
startRecording();
Toast.makeText(context, "started", Toast.LENGTH_SHORT).show();
}
break;
case TelephonyManager.CALL_STATE_RINGING:
break;
}
}
}
};
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(getApplicationContext(), "Service Created", Toast.LENGTH_LONG).show();
IntentFilter RecFilter = new IntentFilter();
RecFilter.addAction("android.intent.action.PHONE_STATE");
RecFilter.addAction("android.intent.action.NEW_OUTGOING_CALL");
registerReceiver(myreceiver, RecFilter);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(myreceiver);
Toast.makeText(getApplicationContext(), "Service destroyed", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
// startRecording();
return START_STICKY;
}
void startRecording(){
String root="/sdcard/";
String fname="rec"+System.currentTimeMillis()+".amr";
File file=new File(root,fname);
callrecorder=new MediaRecorder();
callrecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
callrecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
callrecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
callrecorder.setOutputFile(file.getAbsolutePath()
);
try {
callrecorder.prepare();
callrecorder.start();
recording=true;
// Toast.makeText(getApplicationContext(), "Started", Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
// Toast.makeText(getApplicationContext(),e.printStackTrace(),3000 ).show();
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void stopRecording(){
callrecorder.stop();
// callrecorder.release();
callrecorder.reset();
recording=false;
}
}
MainActivity.java
public class MainActivity extends Activity {
Intent intent2;
static MediaRecorder callrecorder;
static Boolean recording=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnStart=(Button)findViewById(R.id.button1);
Button btnStop=(Button)findViewById(R.id.button2);
btnStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Start Service", 10000).show();
intent2 = new Intent(getApplicationContext(), cRecordingservice.class);
// getApplicationContext().startService(intent2);
}
});
btnStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Stop Service", 10000).show();
intent2 = new Intent(getApplicationContext(), cRecordingservice.class);
getApplicationContext().stopService(intent2);
}
});
}
}
Below is the manifest code
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.crecording.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>
<receiver android:name="com.example.crecording.callReceiver" >
<intent-filter >
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
<service android:name="com.example.crecording.cRecordingservice" ></service>
</application>
After changes app is able to record one call but after that it makes file of unrecognised format & append file to the current file.I dont know why this happens
It looks like you start your recording service when the phone state changes (for example, from "idle" to "offhook"). But then in that service you don't register your broadcast receiver to listen for phone state changes and you also don't ever start recording, so nothing ever happens.
You should pass data to the service to tell it the phone state change when it starts, then make sure you register your broadcast receiver when it starts. You will also need to handle the fact that you now have two broadcast receivers listening for phone state changes and possibly starting and stopping your recording.

Categories