I have been trying to get my app to stop playing music when the phone is ringing, but it isn't working. I've tried everything, but it seems impossible. Here's the code.
package com.beanie.samples.streaming;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import com.beanie.samples.streaming.R;
import com.beanie.samples.streaming.MyService;
import android.app.Activity;
import android.app.IntentService;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
public class HomeActivity extends Activity implements OnClickListener {
private static final String TAG = "MyServices";
private final static String RADIO_STATION_URL = "http://195.154.237.162:8936/";
private static final String START_STICKY = null;
Button buttonPlay, buttonStopPlay;
/** Called when the activity is first created.
* Keep this here all the application will stop working */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay.setOnClickListener(this);
}
private ProgressBar playSeekBar;
private MediaPlayer player;
private InputStream recordingStream;
private RecorderThread recorderThread;
private boolean isRecording = false;
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Toast.makeText(this, "Buffering ", percent).show();
Log.i("Buffering", "" + percent);
}
public class GetCallerInfoActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
// register PhoneStateListener
PhoneStateListener callStateListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber) {
// If phone ringing
if (state==TelephonyManager.CALL_STATE_RINGING) {
stopPlaying();
}
// If incoming call received
if (state==TelephonyManager.CALL_STATE_OFFHOOK) {
stopPlaying();
}
if (state==TelephonyManager.CALL_STATE_IDLE) {
Toast.makeText(getApplicationContext(),"phone is neither ringing nor in a call", Toast.LENGTH_LONG).show();
}
}
};
telephonyManager.listen(callStateListener,PhoneStateListener.LISTEN_CALL_STATE);
}
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
player.setLooping(false); // Set looping
} else if (v == buttonStopPlay) {
Log.d(TAG, "onClick: stopping srvice");
stopPlaying();
}
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
stopRecording();
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource(RADIO_STATION_URL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void startRecording() {
BufferedOutputStream writer = null;
try {
URL url = new URL(RADIO_STATION_URL);
URLConnection connection = url.openConnection();
final String FOLDER_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + "Songs";
File folder = new File(FOLDER_PATH);
if (!folder.exists()) {
folder.mkdir();
}
writer = new BufferedOutputStream(new FileOutputStream(new File(FOLDER_PATH
+ File.separator + "sample.mp3")));
recordingStream = connection.getInputStream();
final int BUFFER_SIZE = 100;
byte[] buffer = new byte[BUFFER_SIZE];
while (recordingStream.read(buffer, 0, BUFFER_SIZE) != -1 && isRecording) {
writer.write(buffer, 0, BUFFER_SIZE);
writer.flush();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
recordingStream.close();
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void stopRecording() {
try {
isRecording = false;
if (recordingStream != null) {
recordingStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private class RecorderThread extends Thread {
#Override
public void run() {
isRecording = true;
startRecording();
}
};
}
Could someone please help and implement this? I would appreciate and it and it would help a lot. Also, I have even helped myself by trying.
You need to use the TelephonyManager
mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
mTelephonyMgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
The listener object can be created like this
private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
// Test for incoming call, dialing call, active or on hold
if (state==TelephonyManager.CALL_STATE_RINGING || state==TelephonyManager.CALL_STATE_OFFHOOK)
{
stop(); // Put here the code to stop your music
}
super.onCallStateChanged(state, incomingNumber);
}
};
When stopping, or closing your app, remember to call this.
mTelephonyMgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
Related
I want my app to write to my bluetooth receiver commend until i hold a button, then the commend will change and continue when i release. (it will send 0 always until i will hold, and then it will send 1 and when i release 0 again).
I tried to make a thread it will send the 0 that is working but when i hold the button it sends 1(as intened) but when i release it doesnt sends 0 again.
package com.example.bluetooth;
import static android.text.TextUtils.concat;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelUuid;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private OutputStream outputStream;
Spinner spinner;
ArrayList<String> deviceName = new ArrayList<String>();
Map<String, String> devicesDict = new HashMap<String, String>();
Object[] devices;
EditText InputTI;
Button sendB;
Button commend1B;
String message;
Boolean connected = false;
Boolean sending = false;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
if(bondedDevices.size() > 0) {
devices = (Object []) bondedDevices.toArray();
Log.i("devices:","devices[0]"+devices[0]);
Log.i("devices:","devices[1]"+devices[1]);
Log.i("devices:","devices[2]"+devices[2]);
BluetoothDevice result = null;
for (BluetoothDevice device : bondedDevices) {
devicesDict.put(""+device.getName(), ""+device);
}
Log.i("dict","dict"+devicesDict);
deviceName.add("Select:");
for(Map.Entry<String,String> entry : devicesDict.entrySet()){
deviceName.add(entry.getKey()+";"+entry.getValue());
}
spinner = (Spinner) findViewById(R.id.ListSp);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, deviceName);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
Log.e("error", "No appropriate paired devices.");
} else {
Log.e("error", "Bluetooth is disabled.");
}
}
InputTI = findViewById(R.id.InputTI);
sendB = findViewById(R.id.sendB);
commend1B = findViewById(R.id.commend1B);
Thread thread = new Thread(runnable);
commend1B.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
sending = true;
try {
Log.i("sending","sending 1");
write("1#");
} catch (IOException e) {
e.printStackTrace();
}
sending = false;
return false;
}
});
sendB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i("sendState","state"+sending);
message = InputTI.getText().toString()+"#";
try {
write(message);
} catch (IOException e) {
e.printStackTrace();
}
}
});
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String[] splitted;
splitted = adapterView.getSelectedItem().toString().split(";");
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
if (!adapterView.getSelectedItem().toString().equals("Select:")) {
for (Object o : devices) {
if (o.toString().equals(splitted[1])) {
connected = true;
BluetoothDevice device = (BluetoothDevice) o;
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = null;
try {
socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
} catch (IOException e) {
e.printStackTrace();
}
try {
socket.connect();
} catch (IOException e) {
Log.e("ConnectFail", "Socket.connect() Failed", e);
//e.printStackTrace();
break;
}
try {
outputStream = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
if (connected && !sending) {
Log.i("sending", "sending 021");
thread.start();
}
}
}
}else{
connected = false;
}
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
Runnable runnable = new Runnable(){
public void run() {
while (connected && !sending) {
try {
Log.i("sending", "sending 0");
write("0#");
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
public void write(String s) throws IOException {
outputStream.write(s.getBytes());
}
To run background services you need to use Service class or/and Background Threads.
Service documentation: https://developer.android.com/guide/components/services
BackGround Threads: https://developer.android.com/guide/background/threading
I have this code of main activity, I'm trying to make FTP server app but the problem which I'm getting is that when I click on Change directory button it shows internal storage path and I want both, internal and SD card storage. So please somebody help me solve this issue.
This is the code of main activity:
package com.project.shrey.ftptrial;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import net.rdrei.android.dirchooser.DirectoryChooserActivity;
import net.rdrei.android.dirchooser.DirectoryChooserConfig;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.ftplet.FtpSession;
import org.apache.ftpserver.ftplet.Ftplet;
import org.apache.ftpserver.ftplet.FtpletContext;
import org.apache.ftpserver.ftplet.FtpletResult;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.apache.ftpserver.usermanager.SaltedPasswordEncryptor;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.WritePermission;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
Window window ;
TextView mAddrReg, mAddriOS, mPrompt, mPasswdDisp, mUserDisp, mDirAddress;
EditText mUser, mPasswd;
Switch mTogglePass;
LinearLayout mAddr1, mAddr2;
TextInputLayout mUserParent, mPasswdParent;
Button mDirChooser;
static String pass;
final int MY_PERMISSIONS_REQUEST = 2203;
final int REQUEST_DIRECTORY = 2108;
FtpServerFactory serverFactory = new FtpServerFactory();
ListenerFactory factory = new ListenerFactory();
PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
FtpServer finalServer;
Toolbar toolbar;
boolean justStarted = true;
#SuppressLint("AuthLeak")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(Build.VERSION.SDK_INT>=21){
window =this.getWindow();
window.setStatusBarColor(this.getResources().getColor(R.color.colordarkblue));
}
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.dialog_message).setTitle(R.string.dialog_title);
builder.setPositiveButton("OK", (dialog, id) -> {
dialog.dismiss();
justStarted = false;
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST);
});
builder.show();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST);
}
}
mTogglePass = findViewById(R.id.togglePass);
mTogglePass.setEnabled(false);
mTogglePass.setChecked(false);
mUserParent = findViewById(R.id.userParent);
mUser = findViewById(R.id.user);
mUserDisp = findViewById(R.id.userDisp);
mPasswd = findViewById(R.id.passwd);
mPasswdDisp = findViewById(R.id.passwdDisp);
mPasswdParent = findViewById(R.id.passwdParent);
mPrompt = findViewById(R.id.prompt);
mAddrReg = findViewById(R.id.addrReg);
mAddr2 = findViewById(R.id.addr2);
mAddrReg.setText(String.format("ftp://%s:2121", wifiIpAddress(this)));
mAddriOS = findViewById(R.id.addriOS);
mAddr1 = findViewById(R.id.addr1);
mAddriOS.setText(String.format("ftp://ftp:ftp#%s:2121", wifiIpAddress(this)));
mDirAddress = findViewById(R.id.dirAddress);
mDirChooser= findViewById(R.id.dirChooser);
mDirChooser.setOnClickListener(view -> {
final Intent chooserIntent = new Intent(this, DirectoryChooserActivity.class);
final DirectoryChooserConfig config = DirectoryChooserConfig.builder()
.newDirectoryName("New Folder")
.allowNewDirectoryNameModification(true)
.build();
chooserIntent.putExtra(DirectoryChooserActivity.EXTRA_CONFIG, config);
startActivityForResult(chooserIntent, REQUEST_DIRECTORY);
});
finalServer = serverFactory.createServer();
toolbar.setOnClickListener(view -> {
try {
if (checkWifiOnAndConnected(this) || wifiHotspotEnabled(this)) {
MainActivity.this.serverControl();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.dialog_wifi_message).setTitle(R.string.dialog_wifi_title);
builder.setPositiveButton("OK", (dialog, id) -> dialog.dismiss());
builder.show();
}
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
});
mTogglePass.setOnCheckedChangeListener((compoundButton, b) -> {
if (b) {
mPasswdDisp.setText(String.format("Password: %s", pass));
} else {
StringBuilder strB = new StringBuilder("Password: ");
for (int i=0; i < pass.length(); i++) {
strB.append('*');
}
mPasswdDisp.setText(strB.toString());
}
});
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST: {
if (grantResults.length <= 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.dialog_message_exit).setTitle(R.string.dialog_title);
builder.setPositiveButton("OK", (dialog, id) -> {
dialog.dismiss();
finish();
});
builder.show();
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_DIRECTORY) {
if (resultCode == DirectoryChooserActivity.RESULT_CODE_DIR_SELECTED) {
mDirAddress.setText(data.getStringExtra(DirectoryChooserActivity.RESULT_SELECTED_DIR));
}
}
}
#Override
protected void onDestroy() {
try {
finalServer.stop();
} catch (Exception e) {
Log.e("Server Close Error", e.getCause().toString());
}
super.onDestroy();
}
private void setupStart(String username, String password, String subLoc) throws FileNotFoundException {
factory.setPort(2121);
serverFactory.addListener("default", factory.createListener());
File files = new File(Environment.getExternalStorageDirectory().getPath() + "/users.properties");
if (!files.exists()) {
try {
files.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
userManagerFactory.setFile(files);
userManagerFactory.setPasswordEncryptor(new SaltedPasswordEncryptor());
UserManager um = userManagerFactory.createUserManager();
BaseUser user = new BaseUser();
user.setName(username);
user.setPassword(password);
String home = Environment.getExternalStorageDirectory().getPath() + "/" + subLoc;
user.setHomeDirectory(home);
List<Authority> auths = new ArrayList<>();
Authority auth = new WritePermission();
auths.add(auth);
user.setAuthorities(auths);
try {
um.save(user);
} catch (FtpException e1) {
e1.printStackTrace();
}
serverFactory.setUserManager(um);
Map<String, Ftplet> m = new HashMap<>();
m.put("miaFtplet", new Ftplet()
{
#Override
public void init(FtpletContext ftpletContext) throws FtpException {
}
#Override
public void destroy() {
}
#Override
public FtpletResult beforeCommand(FtpSession session, FtpRequest request) throws FtpException, IOException
{
return FtpletResult.DEFAULT;
}
#Override
public FtpletResult afterCommand(FtpSession session, FtpRequest request, FtpReply reply) throws FtpException, IOException
{
return FtpletResult.DEFAULT;
}
#Override
public FtpletResult onConnect(FtpSession session) throws FtpException, IOException
{
return FtpletResult.DEFAULT;
}
#Override
public FtpletResult onDisconnect(FtpSession session) throws FtpException, IOException
{
return FtpletResult.DEFAULT;
}
});
serverFactory.setFtplets(m);
}
private String wifiIpAddress(Context context) {
try {
if (wifiHotspotEnabled(context)) {
return "192.168.43.1";
}
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return Utils.getIPAddress(true);
}
private boolean wifiHotspotEnabled(Context context) throws InvocationTargetException, IllegalAccessException {
WifiManager manager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
Method method = null;
try {
method = manager.getClass().getDeclaredMethod("isWifiApEnabled");
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
method.setAccessible(true); //in the case of visibility change in future APIs
return (Boolean) method.invoke(manager);
}
private boolean checkWifiOnAndConnected(Context context) {
WifiManager wifiMgr = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
assert wifiMgr != null;
if (wifiMgr.isWifiEnabled()) { // Wi-Fi adapter is ON
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
return wifiInfo.getNetworkId() != -1;
}
else {
return false; // Wi-Fi adapter is OFF
}
}
#Override
public void onBackPressed() {
finalServer.stop();
findViewById(R.id.toolbar).setEnabled(false);
toolbar.setBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.colorbluelight, null));
super.onBackPressed();
}
void serverControl() {
if (finalServer.isStopped()) {
mUser.setEnabled(false);
mPasswd.setEnabled(false);
mDirChooser.setEnabled(false);
String user = mUser.getText().toString();
String passwd = mPasswd.getText().toString();
if (user.isEmpty()) {
user = "ftp";
}
if (passwd.isEmpty()) {
passwd = "ftp";
}
String subLoc = mDirAddress.getText().toString().substring(20);
pass = passwd;
StringBuilder strB = new StringBuilder("Password: ");
for (int i=0; i < pass.length(); i++) {
strB.append('*');
}
mPasswdDisp.setText(strB.toString());
mUserDisp.setText(String.format("Username: %s", user));
mUserDisp.setVisibility(View.VISIBLE);
mUserParent.setVisibility(View.INVISIBLE);
mPasswdParent.setVisibility(View.INVISIBLE);
mPasswdDisp.setVisibility(View.VISIBLE);
try {
setupStart(user, passwd, subLoc);
} catch (FileNotFoundException fnfe) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.dialog_message_error).setTitle(R.string.dialog_title);
builder.setPositiveButton("OK", (dialog, id) -> {
dialog.dismiss();
justStarted = false;
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST);
});
builder.show();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST);
}
}
try {
finalServer.start();
mAddrReg.setText(String.format("ftp://%s:2121", wifiIpAddress(this)));
mAddriOS.setText(String.format("ftp://%s:%s#%s:2121", user, passwd, wifiIpAddress(this)));
} catch (FtpException e) {
e.printStackTrace();
}
toolbar.setBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.colordarkblue, null));
mPrompt.setVisibility(View.VISIBLE);
mAddr1.setVisibility(View.VISIBLE);
mAddr2.setVisibility(View.VISIBLE);
mTogglePass.setEnabled(true);
} else if (finalServer.isSuspended()) {
finalServer.resume();
toolbar.setBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.colordarkblue, null));
mPrompt.setVisibility(View.VISIBLE);
mAddr1.setVisibility(View.VISIBLE);
mAddr2.setVisibility(View.VISIBLE);
} else {
finalServer.suspend();
toolbar.setBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.colorbluelight, null));
mPrompt.setVisibility(View.INVISIBLE);
mAddr1.setVisibility(View.INVISIBLE);
mAddr2.setVisibility(View.INVISIBLE);
}
}
}
I'm trying to create a WiFiP2P to communicate with 2 android phones and one Raspberry Pi. I want one phone as host and the second phone + Raspberry Pi as clients.
Until know i could create a test APP to connect the 2 phones via Wifi direct (tested successful). I was following a great tutorial on Youtube Wifi P2P. Unfortunately the tutorial just show how to connect one host with one client and not multiple clients.
I was trying to follow the Android developer guide, but I have not enough experience to understand everything.
I hope you guys can help me to understand what I have to change in my code and explain me why.
The following code is the exact copy from the mentioned tutorial.
Here my MainActivity:
package com.example.wifip2p;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pGroup;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button btnOnOff, btnDiscover, btnSend;
ListView listView;
TextView read_msg_box, connectionStatus;
EditText writeMsg;
WifiManager wifiManager;
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
String[] deviceNameArray;
WifiP2pDevice[] deviceArray;
static final int MESSAGE_READ=1;
ServerClass serverClass;
ClientClass clientClass;
SendReceive sendReceive;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1);
}
initialWork();
exqListener();
}
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what){
case MESSAGE_READ:
byte[] readBuff = (byte[])msg.obj;
String tempMsg = new String(readBuff,0,msg.arg1);
read_msg_box.setText(tempMsg);
break;
}
return true;
}
});
private void exqListener() {
btnOnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(wifiManager.isWifiEnabled()){
wifiManager.setWifiEnabled(false);
btnOnOff.setText("ON");
if(mManager!=null) {
mManager.removeGroup(mChannel, null);
}
}else{
wifiManager.setWifiEnabled(true);
btnOnOff.setText("OFF");
}
}
});
btnDiscover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
connectionStatus.setText("Discovery Started");
}
#Override
public void onFailure(int reason) {
connectionStatus.setText("Discovery Starting Failed");
}
});
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
final WifiP2pDevice device = deviceArray[i];
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(getApplicationContext(),"Connected to " + device.deviceName, Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(int reason) {
Toast.makeText(getApplicationContext(),"Not Connected",Toast.LENGTH_SHORT).show();
}
});
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = writeMsg.getText().toString();
Toast.makeText(getApplicationContext(),"MSG: " + msg,Toast.LENGTH_SHORT).show();
sendReceive.write(msg.getBytes());
}
});
}
private void initialWork() {
btnOnOff= findViewById(R.id.onOff);
btnDiscover = findViewById(R.id.discover);
btnSend = findViewById(R.id.sendButton);
listView = findViewById(R.id.peerListView);
read_msg_box = findViewById(R.id.readMsg);
connectionStatus = findViewById(R.id.connectionStatus);
writeMsg = findViewById(R.id.writeMsg);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(),null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
}
WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
if(!peerList.getDeviceList().equals(peers)){
peers.clear();
peers.addAll(peerList.getDeviceList());
deviceNameArray = new String[peerList.getDeviceList().size()];
deviceArray = new WifiP2pDevice[peerList.getDeviceList().size()];
int index = 0;
for(WifiP2pDevice device : peerList.getDeviceList()){
deviceNameArray[index] = device.deviceAddress;
deviceArray[index] = device;
index++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,deviceNameArray);
listView.setAdapter(adapter);
}
if(peers.size()==0){
Toast.makeText(getApplicationContext(), "No Devices Found",Toast.LENGTH_SHORT).show();
}
}
};
WifiP2pManager.ConnectionInfoListener connectionInfoListener = new WifiP2pManager.ConnectionInfoListener() {
#Override
public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
final InetAddress groupOwnerAddress = wifiP2pInfo.groupOwnerAddress;
if(wifiP2pInfo.groupFormed && wifiP2pInfo.isGroupOwner){
connectionStatus.setText("Host");
serverClass=new ServerClass();
serverClass.start();
}else if(wifiP2pInfo.groupFormed){
connectionStatus.setText("Client");
clientClass = new ClientClass(groupOwnerAddress);
clientClass.start();
}
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver,mIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
registerReceiver(mReceiver,mIntentFilter);
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
clientClass.socket.close();
serverClass.serverSocket.close();
serverClass.socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void finalize() throws Throwable {
super.finalize();
try {
clientClass.socket.close();
serverClass.serverSocket.close();
serverClass.socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public class ServerClass extends Thread{
Socket socket;
ServerSocket serverSocket;
#Override
public void run() {
// serverSocket= null;
// socket = null;
try {
Log.i("ServerSocket is called", "Called");
serverSocket = new ServerSocket(8888);
socket = serverSocket.accept();
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class SendReceive extends Thread{
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SendReceive(Socket skt){
socket = skt;
try {
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while(socket!=null){
try {
bytes = inputStream.read(buffer);
if(bytes > 0){
handler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write (byte[] bytes){
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ClientClass extends Thread{
Socket socket;
String hostAdd;
public ClientClass(InetAddress hostAddress){
hostAdd = hostAddress.getHostAddress();
// socket = null;
socket = new Socket();
}
#Override
public void run() {
try {
socket.connect(new InetSocketAddress(hostAdd,8888),500);
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here my BroadcastReceiver Class:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pManager;
import android.nfc.Tag;
import android.util.Log;
import android.widget.Toast;
import static android.content.ContentValues.TAG;
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;
public WiFiDirectBroadcastReceiver(WifiP2pManager mManager, WifiP2pManager.Channel mChannel, MainActivity mActivity)
{
this.mManager = mManager;
this.mChannel = mChannel;
this.mActivity = mActivity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE,-1);
if(state==WifiP2pManager.WIFI_P2P_STATE_ENABLED){
Toast.makeText(context,"Wifi is ON",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context,"Wifi is OFF",Toast.LENGTH_SHORT).show();
}
}else if(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)){
if(mManager!=null){
mManager.requestPeers(mChannel,mActivity.peerListListener);
}
Log.d(TAG, "onReceive: P2P peers changed");
}else if(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)){
if(mManager==null){
return;
}
NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if(networkInfo.isConnected()){
mManager.requestConnectionInfo(mChannel,mActivity.connectionInfoListener);
}else{
mActivity.connectionStatus.setText("Device Disconnected");
}
}else if(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)){
//do something
}
}
}
I have tried to get this working so that it plays in the background?? why won't it work it looks fine to me??
I am new to java/android development so hope someone can fix the issue and explain what I problem was so I can learn something
Yes I got it to stream so far but once you exit the app the music stops playing
For being new think im doing great must be since I have previous experience with PHP etc..
Thanks ;)
package com.beanie.samples.streaming;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import com.beanie.samples.streaming.R;
import com.beanie.samples.streaming.MyService;
import android.app.Activity;
import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
;
public class HomeActivity extends Activity implements OnClickListener {
private static final String TAG = "MyServices";
private final static String RADIO_STATION_URL = "http://195.154.237.162:8936/";
private static final String START_STICKY = null;
Button buttonPlay, buttonStopPlay;
/** Called when the activity is first created.
* Keep this here all the application will stop working */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay.setOnClickListener(this);
}
private ProgressBar playSeekBar;
private MediaPlayer player;
private InputStream recordingStream;
private RecorderThread recorderThread;
private boolean isRecording = false;
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
public void onClick(View v) {
if (v == buttonPlay) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MyService.class));
startPlaying();
player.setLooping(false); // Set looping
} else if (v == buttonStopPlay) {
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
stopPlaying();
}
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
stopRecording();
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource(RADIO_STATION_URL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
private void startRecording() {
BufferedOutputStream writer = null;
try {
URL url = new URL(RADIO_STATION_URL);
URLConnection connection = url.openConnection();
final String FOLDER_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + "Songs";
File folder = new File(FOLDER_PATH);
if (!folder.exists()) {
folder.mkdir();
}
writer = new BufferedOutputStream(new FileOutputStream(new File(FOLDER_PATH
+ File.separator + "sample.mp3")));
recordingStream = connection.getInputStream();
final int BUFFER_SIZE = 100;
byte[] buffer = new byte[BUFFER_SIZE];
while (recordingStream.read(buffer, 0, BUFFER_SIZE) != -1 && isRecording) {
writer.write(buffer, 0, BUFFER_SIZE);
writer.flush();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
recordingStream.close();
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void stopRecording() {
try {
isRecording = false;
if (recordingStream != null) {
recordingStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private class RecorderThread extends Thread {
#Override
public void run() {
isRecording = true;
startRecording();
}
};
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
well, it is stopping because you're asking it to stop.
When the activity goes to background it pauses.
You should run the stream from a service (that stays in the background without issues) and use a bound service to communicate between activity and service http://developer.android.com/guide/components/bound-services.html
How would I stop music playing so call the OnPause if there is a incoming or outgoing call?
So once there is a call or they make a call it will stop the music by calling OnPause.
package com.beanie.samples.streaming;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import com.beanie.samples.streaming.R;
import com.beanie.samples.streaming.MyService;
import android.app.Activity;
import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
;
public class HomeActivity extends Activity implements OnClickListener {
private static final String TAG = "MyServices";
private final static String RADIO_STATION_URL = "http://195.154.237.162:8936/";
private static final String START_STICKY = null;
Button buttonPlay, buttonStopPlay;
/** Called when the activity is first created.
* Keep this here all the application will stop working */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay.setOnClickListener(this);
}
private ProgressBar playSeekBar;
private MediaPlayer player;
private InputStream recordingStream;
private RecorderThread recorderThread;
private boolean isRecording = false;
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void getTelephonyOverview(final TelephonyManager telMgr)
{
int callState = telMgr.getCallState();
String callStateString = "NA";
switch (callState) {
case TelephonyManager.CALL_STATE_IDLE:
getLastCallLogEntry(Appinfo.this);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.i("Call","started");
break;
case TelephonyManager.CALL_STATE_RINGING:
Log.i("Call","ringing");
break;
}
}
public void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Toast.makeText(this, "Buffering ", percent).show();
Log.i("Buffering", "" + percent);
}
public void onClick(View v) {
if (v == buttonPlay) {
onBufferingUpdate(player, 0);
Log.d(TAG, "onClick: starting srvice");
startPlaying();
player.setLooping(false); // Set looping
}
else if (v == buttonStopPlay) {
Log.d(TAG, "onClick: stopping srvice");
stopPlaying();
}
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
stopRecording();
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource(RADIO_STATION_URL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void startRecording() {
BufferedOutputStream writer = null;
try {
URL url = new URL(RADIO_STATION_URL);
URLConnection connection = url.openConnection();
final String FOLDER_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + "Songs";
File folder = new File(FOLDER_PATH);
if (!folder.exists()) {
folder.mkdir();
}
writer = new BufferedOutputStream(new FileOutputStream(new File(FOLDER_PATH
+ File.separator + "sample.mp3")));
recordingStream = connection.getInputStream();
final int BUFFER_SIZE = 100;
byte[] buffer = new byte[BUFFER_SIZE];
while (recordingStream.read(buffer, 0, BUFFER_SIZE) != -1 && isRecording) {
writer.write(buffer, 0, BUFFER_SIZE);
writer.flush();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
recordingStream.close();
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void stopRecording() {
try {
isRecording = false;
if (recordingStream != null) {
recordingStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private class RecorderThread extends Thread {
#Override
public void run() {
isRecording = true;
startRecording();
}
};
}
how would I stop music playing so call the OnPause
onPause() and onStop() are lifecycle methods that will be called automatically; you do not call them manually. You should override them and add your code that would stop the music.
You don't need to do anything in your lifecycle methods to stop the music. Android provides you with a mechanism to handle these cases.
The mechanism is called Audio Focus. Apps request Audio Focus when they want to play audio (or video!). When another app needs audio, it requests the Audio Focus. And the subscribed parties receive a broadcast saying: Hey, you've lost the audio focus. If the focus was only temporarily lost (like when a notification comes and it plays a short audio beep) then the Broadcast says: Hey, you've lost the audio focus but duck the audio, I'll give it back in a moment.
The idea in that case is that you lower (duck) your volume to 0.1 (for example) to let the other sound (beep) be louder.
After the "beep" from the notification is done, the broadcast says: hey, here's the audio focus you had earlier.
At this point if you're still playing, you'd restore the volume to what it was before.
That's the concept behind audio focus. It's perfectly explained in the Android Docs (and the Android Samples) albeit the Google code is rather messy and inconsistent, it does work out of the box. They do a lot of crappy abstraction and some strange code practices but irregardless of that, the code works fine.
The same goes for a phone call, you subscribe to it and tell your service to pause/resume the sound when there's a call in progress. Not when your app goes to the background (onpause) because that's unreliable and doesn't mean at all that you app went to the background.
Here's the Android Official Docs for Audio Focus.