I am using wifi direct to send file between two android phones.
sender code:
OutputStream outputStream = null;
InputStream inputStream = null;
try {
outputStream = socket.getOutputStream();
inputStream = new FileInputStream(exportTempFile);
byte[] buf = new byte[socket.getSendBufferSize()];
int len = 0;
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.flush();
return 0;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
receiver code:
OutputStream outputStream = null;
InputStream inputStream = null;
try {
tempDir = new File(context.getCacheDir(), "temp");
if (!tempDir.exists()) {
tempDir.mkdir();
}
File file = new File(tempDir, "temp.zip");
file.createNewFile();
outputStream = new FileOutputStream(file);
inputStream = socket.getInputStream();
byte[] buf = new byte[socket.getReceiveBufferSize()];
int len = 0;
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
outputStream.flush();
}
return file;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
However, I always get "W/System.err" at the receiver side when running bytestream.copy . I wonder if I did something wrong. Did I close socket too early so the other side can not get data?
error is as below:
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ java.net.SocketException: recvfrom failed: ETIMEDOUT (Connection timed out)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java:545)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.IoBridge.recvfrom(IoBridge.java:509)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at java.io.InputStream.read(InputStream.java:163)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at cc.megaman.led.service.ImportManager$ImportTask.doInBackground(ImportManager.java:420)
10-15 17:13:50.172 13921-14306/cc.megaman.led W/System.err﹕ at cc.megaman.led.service.ImportManager$ImportTask.doInBackground(ImportManager.java:377)
10-15 17:13:50.172 13921-14306/cc.megaman.led W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-15 17:13:50.172 13921-14306/cc.megaman.led W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
10-15 17:13:50.172 13921-14306/cc.megaman.led W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
10-15 17:13:50.172 13921-14306/cc.megaman.led W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ Caused by: libcore.io.ErrnoException: recvfrom failed: ETIMEDOUT (Connection timed out)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.Posix.recvfromBytes(Native Method)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.Posix.recvfrom(Posix.java:140)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:164)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.IoBridge.recvfrom(IoBridge.java:506)
Related
I've created a button that creates a file then sends it as an attachment to an email,
it grabs the text from one of the textviews, saves it to a .txt and sends it. A small email service option selector should show up too. The code is meant to create a file path if one is not already there. This code is above the onCreate method and in a regular activity.
i keep getting this in the logcat (specific message marked by (-->)):
-->08-06 12:53:01.019 18432-18432/com.example.adrian.trucktracker W/System.err﹕ java.io.IOException: open failed: ENOENT (No such file or directory)<---
08-06 12:53:01.019 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.io.File.createNewFile(File.java:946)
08-06 12:53:01.019 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at com.example.adrian.trucktracker.Locator.clickedUpdate(Locator.java:76)
08-06 12:53:01.019 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
08-06 12:53:01.019 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.view.View$1.onClick(View.java:3860)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.view.View.performClick(View.java:4480)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.view.View$PerformClick.run(View.java:18686)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:733)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.os.Looper.loop(Looper.java:157)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5872)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:852)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:668)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at libcore.io.Posix.open(Native Method)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ at java.io.File.createNewFile(File.java:939)
08-06 12:53:01.029 18432-18432/com.example.adrian.trucktracker W/System.err﹕ ... 15 more
My code:
public void clickedUpdate(View view)
{
TextView dLong = (TextView) findViewById (R.id.textLong);
TextView dLat = (TextView) findViewById (R.id.textLat);
String dataLat = dLat.getText().toString();
String dataLong = dLong.getText().toString();
boolean UpdateResume;
if(!(dataLat.equals("") && !(dataLong.equals(""))))
{
UpdateResume = true;
}
else
{
UpdateResume = false;
}
TelephonyManager telephonemanager =(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
String PhoneNumber = telephonemanager.getLine1Number();
File DataDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"/LocationData");
if(!DataDir.exists())
{
try
{
DataDir.mkdir();
}
catch (Exception e)
{
e.printStackTrace();
}
}
File Data = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"data" + File.separator+"Locationer.txt");
String datapath = Data + ""
if(!Data.exists())
{
try {
line 76 ----> Data.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
while (UpdateResume = true)
{
if (Data.exists())
{
try
{
FileWriter fileWriter = new FileWriter(Data);
BufferedWriter bfWriter = new BufferedWriter(fileWriter);
bfWriter.write(PhoneNumber + "," + dataLat + "," + dataLong);
bfWriter.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
break;
}
}
Intent emailintent = new Intent(Intent.ACTION_SEND);
emailintent.setType("text/plain");
emailintent.putExtra(Intent.EXTRA_EMAIL, new String[]{"apraiswater#legion-logistics.com"});
emailintent.putExtra(Intent.EXTRA_SUBJECT, "Data");
emailintent.putExtra(Intent.EXTRA_TEXT, "Hello World!");
File root = Environment.getExternalStorageDirectory();
String DataAttachment = "Android/data/Locationer.txt";
File filer = new File(root, DataAttachment);
if (!filer.exists() || filer.canRead())
{
return;
}
Uri uri = Uri.fromFile(filer);
emailintent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(emailintent, "Choose an Email provider"));
}
A few details seem relevant:
First you check the existence of the dir:
File DataDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"/LocationData");
if(!DataDir.exists())
{
try
{
DataDir.mkdir();
}
catch (Exception e)
{
e.printStackTrace();
}
}
according to the documentation, your try{}catch(Exception e){} aren't needed. You just would need to check whether the directory actually exists. There's the additional problem that you seem to create a subdirectory of another subdirectory. So, you might want to exchange it to mkdirs() instead.
Afterwards, you try to create the File if it doesn't exist
try {
line 76 ----> Data.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Take a look at the documentation for this method. You might note that it tells you
This method is not generally useful. For creating temporary files, use
createTempFile(String, String) instead. For reading/writing files, use
FileInputStream, FileOutputStream, or RandomAccessFile, all of which
can create files.
but maybe, if you've included the proper permissions, the changes I suggested above will help to make your code work.
i'm new in java and android programming but i accepted a challenge launched by a friend and now i have to work hard.
I finally managed to have this type of activity working with AsyncTask but it seems to work well on all android but not on 4.4.2 KitKat.
The problem seems to be on url.openConnection and i tried many times to change the way in wich i do it but i haven't had positive results...
I have only to read file from an URL
This is my class code:
public class MenuActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
new HttpTask().execute();
}
public final class HttpTask
extends
AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
private HttpClient mHc = new DefaultHttpClient();
#Override
protected String doInBackground(String... params) {
publishProgress(true);
InputStream inputstream = null;
URL url = null;
try {
url = new URL("http://somesite/prova.txt");
} catch (MalformedURLException e) {
e.printStackTrace();
}
assert url != null;
URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputstream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
ByteArrayOutputStream bytearryoutputstream = new ByteArrayOutputStream();
int i;
try {
i = inputstream.read();
while (i != -1) {
bytearryoutputstream.write(i);
i = inputstream.read();
}
inputstream.close();
} catch (IOException e) {
e.printStackTrace();
}
return bytearryoutputstream.toString();
}
#Override
protected void onProgressUpdate(Boolean... progress) {
}
#Override
protected void onPostExecute(String result) {
StringBuilder nuovafrase=new StringBuilder("");
String[] frasone=result.split("\n");
ListView listView = (ListView)findViewById(R.id.listViewDemo);
ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.rowmenu, R.id.textViewList, frasone);
listView.setAdapter(arrayAdapter);
}
}
}
And this is the Logcat...
03-11 17:49:37.955 1277-1294/com.example.appsb.app W/System.err﹕ atjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-11 17:49:37.955 1277-1294/com.example.appsb.app W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at libcore.io.Posix.getaddrinfo(Native Method)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ ... 18 more
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ ... 21 more
03-11 17:49:37.963 1277-1294/com.example.appsb.app W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0xa4d69b20)
03-11 17:49:37.963 1277-1294/com.example.appsb.app E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.appsb.app, PID: 1277
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.example.appsb.app.MenuActivity$HttpTask.doInBackground(MenuActivity.java:74)
at com.example.appsb.app.MenuActivity$HttpTask.doInBackground(MenuActivity.java:33)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
There is a Caused by: java.lang.NullPointerException but i cannot understand why...
Thanks
It could be caused by the inputstream being null. inputstream will only be initialized if the response code is OK. So you need to check what response code is being returned. If it is not causing the error, I'd still add some code for if the response code is not OK. You don't want your app to crash if it can't connect. You should at least display a helpful error message
Example:
else{
showErrorMsg();
return null;
}
Catch FileNotFoundException when trying inputstream.read();
try {
i = inputstream.read();
while (i != -1) {
bytearryoutputstream.write(i);
i = inputstream.read();
}
inputstream.close();
} catch (FileNotFoundException e) {
Log.e("MyTag","Handling empty page...");
} catch (IOException e) {
Log.e("MyTag",e.toString());
}
I have this doInBackground method which records audio streams from the internet. The main work is being done inside while (len != -1) { }. This works fine however the buffer = new byte[] doesn't work as I expected - when the connection is interrupted the IOException is called immidiately and the buffer is not used anymore. How can I make this buffer to "feed" my code till it is empty? I want to have the same behavior like it is in audio players; so first when you connect to the stream (it is buffering), then playing and if the connection is interrupted it is still playing from the buffer (till it is empty).
Recorder:
protected Boolean doInBackground(String... StringUrls) {
boolean fdetermined = false;
Environment env = new Environment();
Calendar c = Calendar.getInstance();
BufferedOutputStream bufOutstream = null;
buffer = new byte[1024 * 10];
int len=-1;
InputStream in = null;
URLConnection conn = null;
try{
conn = new URL(StringUrls[0]).openConnection();
conn.setConnectTimeout(5000);
in = conn.getInputStream();
len = in.read(buffer);
File dir = new File(env.getExternalStorageDirectory() + "/somewhere");
if (!dir.exists()) {
dir.mkdir();
}
filename = env.getExternalStorageDirectory()+"/somewhere/file";
bufOutstream = new BufferedOutputStream(new FileOutputStream(new File(filename)));
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
while (len != -1) {
if(in != null && buffer != null && bufOutstream != null) {
try {
bufOutstream.write(buffer, 0, len);
len = in.read(buffer);
if (Recorder.this.isCancelled) {
Recorder.this.stopSelf();
break;
}
} catch (IOException e) {
e.printStackTrace();
conn = null;
in = null;
}
}
}
try{
if(bufOutstream != null) {
bufOutstream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
IO Exception:
12-16 14:37:16.999 31950-32021/com.app.example W/System.err﹕ java.net.SocketException: recvfrom failed: ETIMEDOUT (Connection timed out)
12-16 14:37:17.059 31950-32021/com.app.example W/System.err﹕ at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java:542)
12-16 14:37:17.109 31950-32021/com.app.example W/System.err﹕ at libcore.io.IoBridge.recvfrom(IoBridge.java:506)
12-16 14:37:17.109 31950-32021/com.app.example W/System.err﹕ at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
12-16 14:37:17.109 31950-32021/com.app.example W/System.err﹕ at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
12-16 14:37:17.119 31950-32021/com.app.example W/System.err﹕ at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
12-16 14:37:17.119 31950-32021/com.app.example W/System.err﹕ at java.io.BufferedInputStream.read(BufferedInputStream.java:304)
12-16 14:37:17.149 31950-32021/com.app.example W/System.err﹕ at libcore.net.http.UnknownLengthHttpInputStream.read(UnknownLengthHttpInputStream.java:41)
12-16 14:37:17.149 31950-32021/com.app.example W/System.err﹕ at java.io.InputStream.read(InputStream.java:163)
12-16 14:37:17.189 31950-32021/com.app.example W/System.err﹕ at com.app.example.Recorder$RecordTask.doInBackground(Recorder.java:376)
12-16 14:37:17.189 31950-32021/com.app.example W/System.err﹕ at com.app.example.Recorder$RecordTask.doInBackground(Recorder.java:288)
12-16 14:37:17.189 31950-32021/com.app.example W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:264)
12-16 14:37:17.189 31950-32021/com.app.example W/System.err﹕ at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:137)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at java.lang.Thread.run(Thread.java:856)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ Caused by: libcore.io.ErrnoException: recvfrom failed: ETIMEDOUT (Connection timed out)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at libcore.io.Posix.recvfromBytes(Native Method)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at libcore.io.Posix.recvfrom(Posix.java:131)
12-16 14:37:17.209 31950-32021/com.app.example W/System.err﹕ at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:164)
12-16 14:37:17.209 31950-32021/com.app.example W/System.err﹕ at libcore.io.IoBridge.recvfrom(IoBridge.java:503)
I have added finally block below:
while (len != -1) {
if(in != null && buffer != null && bufOutstream != null) {
try {
bufOutstream.write(buffer, 0, len);
len = in.read(buffer);
if (Recorder.this.isCancelled) {
Recorder.this.stopSelf();
break;
}
} catch (IOException e) {
e.printStackTrace();
conn = null;
in = null;
}
finally{
//do your work here. This block will execute no matter of what exception is thrown
try{
if(bufOutstream != null) {
bufOutstream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ok so im trying capture the webview on button click, of the web page that is being displayed on my webview activity and save it to the sd card.
i have in my manifest the right permission to write external storage and all webview features are working just great, just when i attempt to capture the image.
public void onClick(View v) {
switch(v.getId()) {
case R.id.button1:
WebViewClientDemoActivity.web.goBack();
break;
case R.id.button2:
WebViewClientDemoActivity.web.goForward();
break;
case R.id.button3:
WebViewClientDemoActivity.web.capturePicture();
//Capture Picture
Picture picture = WebViewClientDemoActivity.web.capturePicture();
//Create a new canvas
Canvas mCanvas = new Canvas();
//Draw the Picture into the Canvas
picture.draw(mCanvas);
//Create a Bitmap
Bitmap sreenshot = Bitmap.createBitmap(picture.getWidth(),
picture.getHeight(),Config.ARGB_8888);
//copy the content fron Canvas to Bitmap
//mCanvas.drawBitmap(mBitmapScreenshot, 0, 0, null);
mCanvas.drawBitmap(sreenshot, 0, 0, null);
//Save the Bitmap to local filesystem
if(sreenshot != null) {
ByteArrayOutputStream mByteArrayOpStream = new
ByteArrayOutputStream();
sreenshot.compress(Bitmap.CompressFormat.JPEG, 90,
mByteArrayOpStream);
try {
File folder = new File(Environment.getExternalStorageDirectory().toString()+"/Enlighten/Images");
folder.mkdirs();
// create a File object for the parent directory
File outputFile = new File(folder, "enlighten.jpg");
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
fos.write(mByteArrayOpStream.toByteArray());
fos.close();
Toast.makeText(WebViewClientDemoActivity.this, "File Created", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(WebViewClientDemoActivity.this, "File Not Found", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
Im getting this error message. (UPDATED)
10-15 11:33:10.336: W/System.err(20577): java.io.FileNotFoundException: /mnt/sdcard/Enlighten/Images/enlighten.jpg: open failed: ENOENT (No such file or directory)
10-15 11:33:10.336: W/System.err(20577): at libcore.io.IoBridge.open(IoBridge.java:406)
10-15 11:33:10.336: W/System.err(20577): at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
10-15 11:33:10.336: W/System.err(20577): at java.io.FileOutputStream.<init>(FileOutputStream.java:73)
10-15 11:33:10.336: W/System.err(20577): at com.jaisonbrooks.enlighten.WebViewClientDemoActivity.onClick(WebViewClientDemoActivity.java:374)
10-15 11:33:10.336: W/System.err(20577): at android.view.View.performClick(View.java:3565)
10-15 11:33:10.336: W/System.err(20577): at android.view.View$PerformClick.run(View.java:14165)
10-15 11:33:10.336: W/System.err(20577): at android.os.Handler.handleCallback(Handler.java:605)
10-15 11:33:10.336: W/System.err(20577): at android.os.Handler.dispatchMessage(Handler.java:92)
10-15 11:33:10.336: W/System.err(20577): at android.os.Looper.loop(Looper.java:137)
10-15 11:33:10.336: W/System.err(20577): at android.app.ActivityThread.main(ActivityThread.java:4517)
10-15 11:33:10.336: W/System.err(20577): at java.lang.reflect.Method.invokeNative(Native Method)
10-15 11:33:10.346: W/System.err(20577): at java.lang.reflect.Method.invoke(Method.java:511)
10-15 11:33:10.346: W/System.err(20577): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
10-15 11:33:10.346: W/System.err(20577): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
10-15 11:33:10.346: W/System.err(20577): at dalvik.system.NativeStart.main(Native Method)
10-15 11:33:10.346: W/System.err(20577): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
10-15 11:33:10.346: W/System.err(20577): at libcore.io.Posix.open(Native Method)
10-15 11:33:10.346: W/System.err(20577): at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
10-15 11:33:10.346: W/System.err(20577): at libcore.io.IoBridge.open(IoBridge.java:390)
The openFileOutput() expects just the file name, without path separators, because it assumes that the file will be created in the app's private data area (if my memory doesn't cheat me then it should be /data/data/[your app package name]/files/).
To create a file on sdcard you can use FileOutputStream directly, see here for an example.
And another advice is that don't use hardcoded path like /mnt/sdcard because the absolute path of sdcard may vary on different devices, instead you should use Environment.getExternalStorageDirectory()
I resolved my issue with this code so it screen captures from inside the menu
public boolean onOptionsItemSelected (MenuItem item){
// Called when you tap a menu item
switch (item.getItemId()){
case R.id.settings_capture:
item.setIcon(R.drawable.capture);
//Resize the webview to the height of the webpage
int pageHeight = web.getContentHeight();
LayoutParams browserParams = web.getLayoutParams();
web.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, pageHeight));
//Capture the webview as a bitmap
web.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(web.getDrawingCache());
web.setDrawingCacheEnabled(false);
//Create the filename to use
String randomFilenamepart = String.valueOf(new SecureRandom().nextInt(1000000));
String filename = Environment.getExternalStorageDirectory().toString() + "/Enlighten_Mobile_" + randomFilenamepart + ".jpg";
File imageFile = new File(filename);
//Stream the file out to external storage as a JPEG
OutputStream fout = null;
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
fout.flush();
fout.close();
Toast.makeText(WebViewClientDemoActivity.this, "Screen Capture Saved!\n\nImage Saved at location : /sdcard\n\nSaved As: Enlighten_Mobile_xxxxx.jpg", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(WebViewClientDemoActivity.this, "Problem with Capturing Image or Location to Store Image", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
} finally {
web.setLayoutParams(browserParams);
}
return true;
I am trying to get the MAC address of my android device without relying on myWifiInfo.getMacAddress()
Following is the code I use:
try{
InetAddress inet = InetAddress.getLocalHost();
NetworkInterface ni = NetworkInterface.getByInetAddress(inet);
byte[] address = ni.getHardwareAddress();
}
catch(Exception e){
Log.d("MyActivity",e.toString());
}
I get the following exception:
08-01 06:10:56.239: WARN/System.err(23164): at java.net.NetworkInterface.rethrowAsSocketException(NetworkInterface.java:212)
08-01 06:10:56.239: WARN/System.err(23164): at java.net.NetworkInterface.collectIpv4Address(NetworkInterface.java:178)
08-01 06:10:56.239: WARN/System.err(23164): at java.net.NetworkInterface.getByName(NetworkInterface.java:118)
08-01 06:10:56.239: WARN/System.err(23164): at java.net.NetworkInterface.getNetworkInterfacesList(NetworkInterface.java:270)
08-01 06:10:56.239: WARN/System.err(23164): at java.net.NetworkInterface.getByInetAddress(NetworkInterface.java:228)
08-01 06:10:56.239: WARN/System.err(23164): at com.example.MyActivity$MyAsyncTask.doInBackground(MyActivity.java:82)
08-01 06:10:56.247: WARN/System.err(23164): at com.example.MyActivity$MyAsyncTask.doInBackground(MyActivity.java:43)
08-01 06:10:56.247: WARN/System.err(23164): at android.os.AsyncTask$2.call(AsyncTask.java:264)
08-01 06:10:56.247: WARN/System.err(23164): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-01 06:10:56.247: WARN/System.err(23164): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-01 06:10:56.247: WARN/System.err(23164): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
08-01 06:10:56.247: WARN/System.err(23164): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-01 06:10:56.247: WARN/System.err(23164): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-01 06:10:56.247: WARN/System.err(23164): at java.lang.Thread.run(Thread.java:856)
08-01 06:10:56.247: WARN/System.err(23164): Caused by: libcore.io.ErrnoException: socket failed: EACCES (Permission denied)
08-01 06:10:56.247: WARN/System.err(23164): at libcore.io.Posix.socket(Native Method)
08-01 06:10:56.247: WARN/System.err(23164): at libcore.io.BlockGuardOs.socket(BlockGuardOs.java:181)
08-01 06:10:56.247: WARN/System.err(23164): at java.net.NetworkInterface.collectIpv4Address(NetworkInterface.java:163)
08-01 06:10:56.247: WARN/System.err(23164): ... 12 more
I have given the permission
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
The exception is thrown from the following line in the code above:
NetworkInterface ni = NetworkInterface.getByInetAddress(inet);
When I log the inet address, I get the same as localhost/127.0.0.1
Can someone please point out the reason for this issue and the solution for the same?
Any help is much appreciated
You can also try following Bluetooth API code to get the MAC address,
private BluetoothAdapter btAdapther;
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
String deviceMacAddress = mBtAdapter.getAddress();
Permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
You can read /sys/class/net/eth0/address as a text file and this file contains the ethernet-MAC-address of eth0 interface, if your device have ethernet hardware.
Sample code may help you:
public String getMac()
{
StringBuffer fileData = new StringBuffer(1000);
try {
BufferedReader reader = new BufferedReader(new FileReader("/sys/class/net/eth0/address"));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
return fileData.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String getMacAddressFromEtcFile(){
try {
return loadFileAsString("/sys/class/net/eth0/address").toUpperCase().substring(0, 17);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static String loadFileAsString(String filePath) throws java.io.IOException{
StringBuffer fileData = new StringBuffer(1000);
BufferedReader reader = new BufferedReader(new FileReader(filePath));
char[] buf = new char[1024];
int numRead = 0;
while((numRead = reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
return fileData.toString();
}