I'm using IntentService to download files from url, using the following code:
package com.example.myapp;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;
public class DownloadService extends IntentService {
private int result = Activity.RESULT_CANCELED;
public static final String URL = "urlpath";
public static final String FILENAME = "filename";
public static final String DOWNLOAD_POSITION = "position";
public static final String FILEPATH = "filepath";
public static final String RESULT = "result";
public static final String PERCENTAGE = "PERCENTAGE";
public static final String FILE_SIZE = "FILESIZE";
public static final String NOTIFICATION = "service receiver";
public static BufferedInputStream bis;
public static long lengthofFile;
public int dnlPosition;
public String fileName;
public DownloadService() {
super("DownloadService");
}
#Override
protected void onHandleIntent(Intent intent) {
String urlPath = intent.getStringExtra(URL);
fileName = intent.getStringExtra(FILENAME);
dnlPosition = intent.getIntExtra("downloadPosition", 0);
File output = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
fileName);
if (output.exists()) {
output.delete();
}
URLConnection streamConnection = null;
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
streamConnection = url.openConnection();
stream = streamConnection.getInputStream();
streamConnection.connect();
lengthofFile = streamConnection.getContentLength();
String fileSize = Long.toString(lengthofFile);
InputStream reader = stream;
bis = new BufferedInputStream(reader);
fos = new FileOutputStream(output.getPath());
int next = -1;
int progress = 0;
int bytesRead = 0;
byte buffer[] = new byte[1024];
while ((bytesRead = bis.read(buffer)) > 0) {
fos.write(buffer, 0, bytesRead);
progress += bytesRead;
int progressUpdate = (int)((progress * 100) / lengthofFile);
Intent testIntent = new Intent("com.example.myapp.MESSAGE_INTENT");
testIntent.putExtra(PERCENTAGE, progressUpdate);
testIntent.putExtra(FILE_SIZE, lengthofFile);
testIntent.putExtra(DOWNLOAD_POSITION, dnlPosition);
testIntent.putExtra(FILENAME, fileName);
sendBroadcast(testIntent);
}
result = Activity.RESULT_OK;
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
publishResults(output.getAbsolutePath(), result);
}
}
it works fine as it is, however if I wanted to cancel an ongoing download, or one of the queued files, i'm still stuck on this step,
I was thinking that i can send a broadcast on cancel button click where the service will listen to it and if the broadcast says break the while ((bytesRead = bis.read(buffer)) > 0) loop it breaks it.
Is this scenario even possible?
Regards
Related
I have a an application which communicates between two android devices through socket. It seems like they do connect, but when data from the client socket is read by ServerSocket (using InputStream), it doesnot return the desired result (it is supposed to return somrthing like "21.24891706//95.23659845//ff8iuj67898n47fu" ).Instead I'm getting " [B#416b9488" as the message.
My client runs an AsyncTask and server runs a Thread.
Can you please help me solve this problem? Any help will is appreciated. Thanks in advance.
Here is Server.java which runs on the server:
import android.content.Context;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
public class Server {
Context context;
ServerSocket serverSocket;
String message = "";
static final int socketServerPORT = 8080;
ShowConnectedStudents activity;
public Server(ShowConnectedStudents callingActivity) {
activity = callingActivity;
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
public int getPort() {
return socketServerPORT;
}
public void onDestroy() {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerThread extends Thread {
int count = 0;
byte buffer[] = new byte[1024];
int bytesRead;
String message;
#Override
public void run() {
try {
// create ServerSocket using specified port
serverSocket=new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(socketServerPORT));
while (true) {
// block the call until connection is created and return
// Socket object
Socket socket = serverSocket.accept();
message = "";
InputStream input = socket.getInputStream();
BufferedInputStream br= new BufferedInputStream(input);
while ((bytesRead = br.read(buffer)) != -1 ) {
message += " " + buffer.toString();
}
message += socket.isConnected();
message+=":"+socket.isClosed();
input.close();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
activity.status.setText("Message is: " + message);
}
});
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Here is Client.java which runs on the client:
import android.os.AsyncTask;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String status = "";
double Lat,Long;
String deviceId;
Socket socket = null;
ConnectToDevice activity;
byte buffer[] = new byte[1024];
int bytesRead;
Client(String addr, int port,double latitude,double longitude,String deviceIdentification,ConnectToDevice callingActivity) {
dstAddress = addr;
dstPort = port;
Lat=latitude;
Long=longitude;
deviceId=deviceIdentification;
activity=callingActivity;
if(dstAddress.charAt(0)=='/'){
dstAddress=dstAddress.substring(1);
}
}
#Override
protected Void doInBackground(Void... arg0) {
while(socket==null){
try {
socket = new Socket(dstAddress, dstPort);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
OutputStream outputStream = socket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream,true);
printStream.print(Lat + "//" + Long+"//"+deviceId);
printStream.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
status = "UnknownHostException: " + e.toString();
} catch (IOException e) {
e.printStackTrace();
status = "IOException: " + e.toString();
} finally {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
activity.statusText.setText(Lat+ "//" + Long+"//"+deviceId);
super.onPostExecute(result);
}
}
toString() on a byte[] is not what you want, you're getting basically the memory address of the byte array
instead convert to a string, something like this
while ((bytesRead = br.read(buffer)) != -1 ) {
message += " " + new String(buffer, 0, bytesRead);
}
I have figured out another way, before reading this accepted answer. I'm posting it in case if it benefit anyone.
My data is text-only. So I wrapped the socket's input stream inside a Scanner.
InputStream input = socket.getInputStream();
Scanner scanner= new Scanner(input);
while(scanner.hasNextLine()){
message+=scanner.nextLine();
}
I want to get two audio files as input, then merge them byte wise and save it as a single file.
In this code I have tried to do it in Java and it's working fine, but I don't know how to do it in android.
How to do it in android?
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
public class FileMixer {
public static void main(String[] args)
{
try
{
Path path1 = Paths.get("C:\\Srini\\Wav\\welcome.wav");
Path path2 = Paths.get("C:\\Srini\\Wav\\goodbye.wav");
String path3 ="C:\\Srini\\Wav\\srini12.wav";
File Newfilepath=new File(path3);
byte[] byte1 = Files.readAllBytes(path1);
byte[] byte2 = Files.readAllBytes(path2);
byte[] out = new byte[byte1.length];
for (int i=0; i<byte1.length; i++)
{
out[i] = (byte) ((byte1[i] + byte2[i]) >> 1);
}
InputStream byteArray = new ByteArrayInputStream(out);
AudioInputStream ais = AudioSystem.getAudioInputStream(byteArray);
AudioSystem.write(ais, AudioFileFormat.Type.WAVE,Newfilepath);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
private void mergeSongs(File mergedFile,File...mp3Files){
FileInputStream fisToFinal = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mergedFile);
fisToFinal = new FileInputStream(mergedFile);
for(File mp3File:mp3Files){
if(!mp3File.exists())
continue;
FileInputStream fisSong = new FileInputStream(mp3File);
SequenceInputStream sis = new SequenceInputStream(fisToFinal, fisSong);
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fisSong.read(buf)) != -1;)
fos.write(buf, 0, readNum);
} finally {
if(fisSong!=null){
fisSong.close();
}
if(sis!=null){
sis.close();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fos!=null){
fos.flush();
fos.close();
}
if(fisToFinal!=null){
fisToFinal.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
For combining two wav files use this code,
import java.io.File;
import java.io.IOException;
import java.io.SequenceInputStream;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
public class WavAppender {
public static void main(String[] args) {
String wavFile1 = "D:\\wavOne.wav";
String wavFile2 = "D:\\wavTwo.wav";
try {
AudioInputStream clip1 = AudioSystem.getAudioInputStream(new File(wavFile1));
AudioInputStream clip2 = AudioSystem.getAudioInputStream(new File(wavFile2));
AudioInputStream appendedFiles =
new AudioInputStream(
new SequenceInputStream(clip1, clip2),
clip1.getFormat(),
clip1.getFrameLength() + clip2.getFrameLength());
AudioSystem.write(appendedFiles,
AudioFileFormat.Type.WAVE,
new File("D:\\wavAppended.wav"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
It is too late. But still, someone might need a proper solution. That is why I am suggesting using AudioMixer-android library. You can also perform a lot of audio processing things.
I'm working on an android app. Lets assume that i have 4 devices (smartphones), two of them are accesspoints and to both of them are connect a device, obvously they are connect via wireless.
So the fact is that i need a way to send data from one subnet to the other, i tried to use multicast (using jmdns library) but without success.
Could anyone help me? Thanks.
I done something similar between pc and smartphone using multicast without any library, just MulticastSocket class in Android and Java backend, did you try that?
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import com.classes.domain.NetworkProperties;
import com.classes.domain.Settings;
public class MulticastSender {
private static ScheduledExecutorService scheduler = null;
public static final String MC_ADDRESS = "226.2.2.3";
public static final int MC_PORT = 8888;
public static final int MAX_LEN = 1024;
public static void startExecutor() {
scheduler = Executors.newScheduledThreadPool(1);
// remove final and uncomment line above if you wanna force automatic
// start
// final Runnable multicastServer = new Runnable() {
Runnable multicastServer = new Runnable() {
#Override
public void run() {
multicastSender();
}
};
scheduler.scheduleAtFixedRate(multicastServer, 0, 10, TimeUnit.SECONDS);
}
public static void multicastSender() {
MulticastSocket socket = null;
InetAddress address = null;
InputStream is = null;
BufferedReader br = null;
int ttl = 1;
String sendData = null;
byte[] sendBytes = null;
try {
socket = new MulticastSocket();
socket.setTimeToLive(ttl);
address = InetAddress.getByName(MC_ADDRESS);
NetworkProperties.retrieveNetworkProperties();
String ip = NetworkProperties.localIPv4Address;
int port = NetworkProperties.applicationPort;
sendData = ip + "-" + port;
is = new ByteArrayInputStream(sendData.getBytes());
br = new BufferedReader(new InputStreamReader(is));
while ((sendData = br.readLine()) != null) {
sendBytes = sendData.getBytes();
DatagramPacket packet = new DatagramPacket(sendBytes, sendBytes.length, address, MC_PORT);
socket.send(packet);
}
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.classes.domain;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.sql.SQLException;
import android.content.Context;
import android.net.wifi.WifiManager;
public class MulticastReceiver {
public static final String MC_ADDRESS = "226.2.2.3";
public static final int MC_PORT = 8888;
public static final int MAX_LEN = 1024;
public static void multicastReceiver(Context context) {
MulticastSocket socket = null;
DatagramPacket packet = null;
InetAddress address = null;
WifiManager.MulticastLock lock = null;
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (wifi != null) {
lock = wifi.createMulticastLock("AllowMulticast");
lock.acquire();
}
try {
socket = new MulticastSocket(MC_PORT);
socket.setReuseAddress(true);
address = InetAddress.getByName(MC_ADDRESS);
socket.joinGroup(address);
while (true) {
byte[] buf = new byte[MAX_LEN];
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String msg = new String(buf, 0, packet.getLength());
// System.out.println("From " + packet.getAddress() + " Msg : "
// + msg);
// System.out.println("Received " + packet.getLength()
// + " bytes from " + packet.getAddress() + ": "
// + new String(packet.getData(), 0, packet.getLength()));
String temp = msg;
/*
REPLACE THIS PART WITH RECEIVED DATA DO WHAT YOU NEED
if (temp.indexOf("-") != -1) {
String[] result = temp.split("-");
String ip = result[0];
String port = result[1];
Settings settings = Settings.loadSettings(context);
settings.setIP(ip);
settings.setPort(Integer.parseInt(port));
try {
settings.Save(context);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
*/
break;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket.leaveGroup(address);
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (lock.isHeld()) {
lock.release();
lock = null;
}
}
}
I want to send an audio file .mp3 file from android client to servlet server and save it in a location. If I play that saved .mp3 file in that location it should play.
My question is there a way to send a .mp3 file directly from client to server and retrieve that mp3 file in servlet.
My client side code is as follows:
package com.android.audiorecord;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.android.audiofileplayer.StreamingMp3Player;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
public class AudioRecordActivity extends Activity
{
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private String url = "QRFileSaveServlet";
String result;
byte[] value;
String s;
byte[] filebyte,clientbyte;
String readString;
private RecordButton mRecordButton = null;
private MediaRecorder mRecorder = null;
private SubmitButton mSubmitButton = null;
private PlayButton mPlayButton = null;
private MediaPlayer mPlayer = null;
String fileresult = "";
HttpResponse response;
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
/* public boolean saveas(int ressound){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
String path="/sdcard/media/audio/ringtones/";
String filename="examplefile"+".ogg";
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "exampletitle");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);
return true;
} */
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
// mRecorder.reset();
mRecorder = null;
}
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
} else {
setText("Start recording");
}
mStartRecording = !mStartRecording;
}
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
}
}
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
};
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
}
}
class SubmitButton extends Button {
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
File f = new File(Environment.getExternalStorageDirectory()+"/audiorecordtest.mp3");
//
//byte[] file = fileresult.getBytes();
try {
filebyte = FileUtils.readFileToByteArray(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("$$$$$$$$$$$" + filebyte);
clientbyte = Base64.encode(filebyte, MODE_APPEND);//(filebyte, MODE_APPEND);
s= new String(clientbyte);
System.out.println("**************" + s);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Audiofile", s));
result = AudioServer.executePost(url, nameValuePairs);
result = result.trim();
System.out.println("response recieved " + result);
if(result!=null){
Bundle bundle = new Bundle();
Intent explicitIntent = new Intent(AudioRecordActivity.this,
StreamingMp3Player.class);
bundle.putString("result", result);
explicitIntent.putExtras(bundle);
startActivity(explicitIntent);
}
}
};
public SubmitButton(Context ctx) {
super(ctx);
setText("Save");
setOnClickListener(clicker);
}
}
public AudioRecordActivity() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.mp3";
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout ll = new LinearLayout(this);
mRecordButton = new RecordButton(this);
ll.addView(mRecordButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mPlayButton = new PlayButton(this);
ll.addView(mPlayButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mSubmitButton = new SubmitButton(this);
ll.addView(mSubmitButton, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, 0));
setContentView(ll);
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
}
in this can i send audiorecordtest.mp3 file direcly to server without encoding to byte[] and send it in namevalue pair.
My server side code is as follows:
package com.gsr.qrbarcode;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import com.android.gsr.utils.AudioSampleReader;
import com.android.gsr.utils.AudioSampleWriter;
import com.android.gsr.utils.Base64;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
//import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFileFormat.Type;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import org.apache.commons.io.FileUtils;
/**
* Servlet implementation class QRFileSaveServlet
*/
//#WebServlet("/QRFileSaveServlet")
public class QRFileSaveServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
AudioInputStream ais;
/**
* Default constructor.
*/
public QRFileSaveServlet() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String qrfile= request.getParameter("Audiofile");
System.out.println("String Parameter \"" +qrfile );
byte[] audiofile=Base64.decode(qrfile);
String newStr = new String(audiofile);
// Display the contents of the byte array.
System.out.println("The new String equals \"" +newStr + "\"");
String filePath = this.getServletContext().getRealPath("/")+"";
System.out.println("Path of the file " + filePath);
String fileupload="AudioFileStorage";
//PrintWriter out = response.getWriter();
File f;
f= new File(filePath);
//int status = 0;
if(f.exists()) {
filePath += fileupload;
f = new File(filePath);
if(!f.exists()){
f.mkdir();
}
f = new File(filePath,"test.mp3");
if(!f.exists()) {
FileOutputStream fos = new FileOutputStream(f);
fos.write(audiofile);
fos.flush();
fos.close();
} else {
//out.println("failure");
ServletOutputStream stream = null;
BufferedInputStream buf = null;
try{
stream = response.getOutputStream();
// File mp3 = new File(mp3Dir + "/" + fileName);
response.setContentType("audio/mpeg");
response.addHeader("Content-Disposition","attachment; filename="+f );
response.setContentLength( (int) f.length() );
FileInputStream input = new FileInputStream(f);
buf = new BufferedInputStream(input);
int readBytes = 0;
while((readBytes = buf.read()) != -1)
stream.write(readBytes);
System.out.println("Response Stream"+stream);
} catch (IOException ioe){
throw new ServletException(ioe.getMessage());
} finally {
if(stream != null)
stream.close();
if(buf != null)
buf.close();
}
}
}
if (filePath == null || filePath.equals(""))
throw new ServletException(
"Invalid or non-existent mp3Dir context-param.");
URL url = null;
try{
url = f.toURL();
System.out.println("URL : "+ url);
System.out.println("Converting process Successfully");
}
catch (MalformedURLException me){
System.out.println("Converting process error");
}
//String rfilepath=this.getServletContext().getRealPath("/")+" AudioFileStorage/test.mp3";
//System.out.println("Path of the rfilepath " + rfilepath);
}
}
here can i get that audiorecordtest.mp3 file directly from client without decoding in server side and play it in this servlet
my server connection in local for client
executepost() is as follows:
package com.android.audio;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class AudioServer {
static InputStream is;
private static String API_URL = "http://192.168.15.71:8088/QRBarCodeServer/";
public static String executePost(String apiurl,
ArrayList<NameValuePair> urlParameters) {
try {
// Create connection
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(API_URL + apiurl);
httppost.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
// Get Response
// InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response1 = new StringBuffer();
while ((line = rd.readLine()) != null) {
response1.append(line);
response1.append('\r');
}
rd.close();
return response1.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String executeHttpGet(String apiurl) throws Exception {
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(API_URL + apiurl);
request.setURI(new URI(apiurl));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
here is simple way to do that
1: from android side read that .mp3 file and create base64String from it.
2: At servier side read this base64String and convert it back to .mp3 file.
to convert any file to base64String following is the process
File file = new File(Environment.getExternalStorageDirectory() + "/hello-4.wav");
byte[] bytes = FileUtils.readFileToByteArray(file);
String encoded = Base64.encodeToString(bytes, 0);
You can reach it using apache MultipartEntity:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(BASE_URL);
MultipartEntity mpEntity = new MultipartEntity();
mpEntity.addPart("Audiofile", new FileBody(file, "audio/mpeg"));
post.setEntity(mpEntity);
HttpResponse res = client.execute(post);
Yea you can send this in Servlet there is Mime type mime means multimedia extension
I am sending code i can guarantee that it will work in Servlet in java and you should take
care for android by own
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SendMp3Envious extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileName = (String) request.getParameter("file");
if (fileName == null || fileName.equals(""))
throw new ServletException(
"Invalid or non-existent file parameter in SendMp3 servlet.");
if (fileName.indexOf(".mp3") == -1)
fileName = fileName + ".mp3";
String mp3Dir = getServletContext().getInitParameter("mp3-dir");
if (mp3Dir == null || mp3Dir.equals(""))
throw new ServletException(
"Invalid or non-existent mp3Dir context-param.");
ServletOutputStream stream = null;
BufferedInputStream buf = null;
try {
stream = response.getOutputStream();
File mp3 = new File(mp3Dir + "/" + fileName);
//set response headers
response.setContentType("audio/mpeg");
response.addHeader("Content-Disposition", "attachment; filename="
+ fileName);
response.setContentLength((int) mp3.length());
FileInputStream input = new FileInputStream(mp3);
buf = new BufferedInputStream(input);
int readBytes = 0;
//read from the file; write to the ServletOutputStream
while ((readBytes = buf.read()) != -1)
stream.write(readBytes);
} catch (IOException ioe) {
throw new ServletException(ioe.getMessage());
} finally {
if (stream != null)
stream.close();
if (buf != null)
buf.close();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Hi I am making a app that fetches a xml file and displays the results with a button labeled get it. I need help with when the button is clicked it will take the .pkg file url in the xml file and download it with some sort of progress reporting. Any help would be awesome thanks in advance. Here is what I have so far it has a error in the download code I tried maybe someone can fix this for me. I am stumped also the links are to .pkg files
package com.mypackagename;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.util.Log;
public class MainActivity extends ListActivity {
String XML_URL = "http://www.mysite.com/book.xml";
private DocumentBuilder docBuilder;
private Document doc;
private DocumentBuilderFactory docBuilderFactory;
private String bookImageUrl;
private int nodeListbooksLength;
private String bookId;
private String bookUrl;
private String bookDescription;
private String bookTitle;
ButtonListMenuAdapter notes;
ArrayList<Book> list;
TextView tv_title;
ImageView iv_logo;
private String Title;
Drawable booksImagesList[];
/** Called when the activity is first created. 1 */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv_title = (TextView) findViewById(R.id.TextView01);
iv_logo = (ImageView) findViewById(R.id.ImageView01);
list = new ArrayList<Book>();
parseXML();
notes = new ButtonListMenuAdapter(
this,
R.layout.book_row,
list );
setListAdapter( notes );
}
private void parseXML()
{
try{
Log.d("MainActivity", "Connecting Server");
InputStream inStream =openHttpConnection(XML_URL);
Log.d("MainActivity", "Fetching Data Completed");
if(inStream!=null){
docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setCoalescing(true);
docBuilder = docBuilderFactory.newDocumentBuilder();
docBuilder.isValidating();
doc = docBuilder.parse(inStream);
NodeList nodeListbookTitle = doc.getDocumentElement().getElementsByTagName("Title1");
if(nodeListbookTitle.getLength()>0){
Element elementbooktitile = (Element) nodeListbookTitle.item(0);
NodeList nodeListElementbooktitle = elementbooktitile.getChildNodes();
if(nodeListElementbooktitle.getLength()>0)
{
Title = ((Node) nodeListElementbooktitle.item(0)).getNodeValue();
Log.d("MainActivity", "Title:"+Title);
tv_title.setText(Title);
}
}
NodeList nodeListbookBanner = doc.getDocumentElement().getElementsByTagName("logo");
if(nodeListbookBanner.getLength()>0){
Element elementTeamBanner = (Element) nodeListbookBanner.item(0);
NodeList nodeListElementTeamBanner = elementTeamBanner.getChildNodes();
if(nodeListElementTeamBanner.getLength()>0)
{
bookImageUrl = ((Node) nodeListElementTeamBanner.item(0)).getNodeValue();
try {
DownloadFilesTask d = new DownloadFilesTask();
d.execute(new URL(bookImageUrl));
d.sendObjectImageView(iv_logo);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("ERROR getView", "EX::"+e);
}
Log.d("MainActivity", "bookImageUrl:"+bookImageUrl);
Log.d("MainActivity", "");
}
}
NodeList nodeListbook = doc.getDocumentElement().getElementsByTagName("Book");
Log.d("MainActivity","nodeListbook Length--"+nodeListbook.getLength());
nodeListbooksLength=nodeListbook.getLength();
booksImagesList = new Drawable[nodeListbooksLength+1];
if(nodeListbooksLength>0){
for(int v=0;v<nodeListbooksLength;v++){
Node nodebook = nodeListbook.item(v);
if (nodebook.getNodeType() == Node.ELEMENT_NODE){
Element elementbookResult = (Element) nodebook;
bookId=elementbookResult.getAttribute("bid");
Log.d("MainActivity","----in bookId- ->"+v+" "+bookId);
bookImageUrl=elementbookResult.getAttribute("bimg");
Log.d("MainActivity","--bookImageUrl--->"+bookImageUrl);
bookTitle=elementbookResult.getAttribute("bte");
Log.d("MainActivity","--bookTitle--->"+bookTitle);
bookDescription=elementbookResult.getAttribute("bsd");
Log.d("MainActivity","--bookDescription--->"+bookDescription);
bookUrl=elementbookResult.getAttribute("bph");
Log.d("MainActivity","--bookUrl:--->"+bookUrl);
list.add( new Book( bookId, bookImageUrl,bookTitle,bookDescription,bookUrl) );
}
}
}
}
}catch(Exception e){
Log.d("MainActivity", "parseXML:"+e);
}
}
private InputStream openHttpConnection(String urlStr) {
InputStream in = null;
int resCode = -1;
try {
Log.d("openHttpConnection", "URL:"+urlStr);
URL url = new URL(urlStr);
URLConnection urlConn = url.openConnection();
if (!(urlConn instanceof HttpURLConnection)) {
throw new IOException ("URL is not an Http URL");
}
Log.d("openHttpConnection", "httpConn:1");
HttpURLConnection httpConn = (HttpURLConnection)urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux "+"i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
Log.d("openHttpConnection", "setting requests and properties");
httpConn.connect();
Log.d("openHttpConnection", "Connected successfully");
resCode = httpConn.getResponseCode();
Log.d("openHttpConnection", "resCode"+resCode);
if (resCode == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
Log.d("openHttpConnection", "Fetchinf data done");
}
} catch (MalformedURLException e) {
e.printStackTrace();
Log.d("openHttpConnection", "1"+e);
} catch (IOException e) {
e.printStackTrace();
Log.d("openHttpConnection", ""+e);
}
return in;
}
private HttpClient httpClient;
private HttpPost httpPost;
private HttpResponse response;
private HttpContext localContext;
private String ret;
private InputStream postPage(String url, String data) {
InputStream is = null;
ret = null;
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpPost = new HttpPost(url);
response = null;
StringEntity tmp = null;
httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux " +
"i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");
httpPost.setHeader("Accept", "text/html,application/xml," +
"application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
try {
tmp = new StringEntity(data,"UTF-8");
} catch (UnsupportedEncodingException e) {
System.out.println("HTTPHelp : UnsupportedEncodingException : "+e);
}
httpPost.setEntity(tmp);
try {
response = httpClient.execute(httpPost,localContext);
} catch (ClientProtocolException e) {
System.out.println("HTTPHelp : ClientProtocolException : "+e);
} catch (IOException e) {
System.out.println("HTTPHelp : IOException : "+e);
}
ret = response.getStatusLine().toString();
HttpEntity he = response.getEntity();
try {
InputStream inStream = he.getContent();
is = inStream;
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return is;
}
class Book
{
public String getBookId() {
return bookId;
}
public String getBookImageUrl() {
return bookImageUrl;
}
public String getBookTitle() {
return bookTitle;
}
public String getBookDescription() {
return bookDescription;
}
public String getBookUrl() {
return bookUrl;
}
private String bookId;
private String bookImageUrl;
private String bookTitle;
private String bookDescription;
private String bookUrl;
public Book(String bookId, String bookImageUrl, String bookTitle,String bookDescription, String bookUrl) {
this.bookId = bookId;
this.bookImageUrl = bookImageUrl;
this.bookTitle = bookTitle;
this.bookDescription = bookDescription;
this.bookUrl = bookUrl;
}
}
public class ButtonListMenuAdapter extends BaseAdapter {
public static final String LOG_TAG = "ButtonListAdapter";
private Context context;
private List<Book> menuList;
private int rowResID;
public ButtonListMenuAdapter(MainActivity context, int rowResID,
ArrayList<Book> menuList) {
// TODO Auto-generated constructor stub
this.context = context;
this.rowResID = rowResID;
this.menuList = menuList;
}
public int getCount() {
return menuList.size();
}
public Object getItem(int position) {
return menuList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final Book row = menuList.get(position);
LayoutInflater inflater = LayoutInflater.from( context );
View v = inflater.inflate( rowResID, parent, false );
TextView tv_title = (TextView)v.findViewById(R.id.Text_book_title);
tv_title.setText(row.getBookTitle());
TextView tv_desc = (TextView)v.findViewById(R.id.Text_Book_Desc);
tv_desc.setText(row.getBookDescription());
ImageView iv_book_img = (ImageView)v.findViewById(R.id.Image_book);
if(booksImagesList[position]==null)
{
try {
DownloadFilesTask d = new DownloadFilesTask();
d.execute(new URL(row.getBookImageUrl()));
d.sendObjectImageView(iv_book_img,position);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("ERROR getView", "EX::"+e);
}
}
else
{
iv_book_img.setImageDrawable(booksImagesList[position]);
Log.d("Not","Reloaded");
}
Button b_get_book = (Button)v.findViewById(R.id.Button01);
b_get_book.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View v) {
private final String PATH = "/mnt/sdcard/"; //put the downloaded file here
public void DownloadFromUrl(String bookUrl, String fileName) { //this is the downloader method
try {
URL url = new URL("http://mysite.com/" + bookUrl); //you can write here any link
File file = new File(fileName);
long startTime = System.currentTimeMillis();
Log.d("ImageManager", "download begining");
Log.d("ImageManager", "download url:" + url);
Log.d("ImageManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(PATH+file);
fos.write(baf.toByteArray());
fos.close();
Log.d("ImageManager", "download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
}
});
return v;
}
}
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
ImageView iv;
int id;
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
downloadDrawable(urls[0].toString());
return totalSize;
}
public void sendObjectImageView(ImageView ivLogo) {
// TODO Auto-generated method stub
this.iv = ivLogo;
id = -1;
}
public void sendObjectImageView(ImageView iv,int id) {
// TODO Auto-generated method stub
this.iv = iv;
this.id = id;
}
protected void onProgressUpdate(Integer... progress) {
Log.d("DownloadFilesTask", "onProgressUpdate"+progress[0]);
}
protected void onPostExecute(Long result) {
Log.d("DownloadFilesTask", "onPostExecute"+result);
if(d!=null && iv!=null)
{
iv.setImageDrawable(d);
if(id!=-1)
booksImagesList[id] = d;
}
}
private Drawable d;
public Drawable downloadDrawable(String imageUrl) {
try {
Log.d("downloadDrawable", "Starting Connection");
URL url = new URL(imageUrl);
URLConnection conn = url.openConnection();
conn.connect();
Log.d("downloadDrawable", "Connection Created Successfully");
InputStream is = conn.getInputStream();
Log.d("downloadDrawable", "InputStream created Successfully");
d = Drawable.createFromStream(is, url.toString());
Log.d("downloadDrawable", "Drawable created Successfully");
is.close();
} catch (IOException e) {
Log.d("ERROR3", "Ex::"+e);
}
return d;
}
}
}
this is a typical http connection.
URL url = new URL(strUrl);
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
InputStream is = urlConn.getInputStream();
final int MAX_LENGTH = 10000;
byte[] buf = new byte[MAX_LENGTH];
int total = 0;
while (total < MAX_LENGTH) {
int count = is.read(buf, total, MAX_LENGTH - total);
if (count < 0) {
break;
}
total += count;
}
is.close();
String result = new String(buf, 0, total);
urlConn.disconnect();