Download Manager not working right - nothing happen after click download button - java

I have problem like in title: Download Manager not working right - I want download file .apk but after click button nothing happens. In logcat I have no errors or warrnings, it not works on emulator and phone as well.
I tried all examples from here(but not only) Download a file with Android, and showing the progress in a ProgressDialog - and still downloading .apk is not starting.
My code:
import android.Manifest;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import java.net.URI;
public class MainActivity extends Activity {
private String url = "https://someurl.com/appplication.apk";
Button btnDownload;
private static final int PERMISSION_STORAGE_CODE = 1000;
private int downloadedProgress = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnDownload = findViewById(R.id.btnDownload);
btnDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_DENIED){
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, PERMISSION_STORAGE_CODE);
} else {
startDownloading();
}
} else {
startDownloading();
}
}
});
}
private void startDownloading(){
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
| DownloadManager.Request.NETWORK_MOBILE);
request.setTitle("Download");
request.setDescription("Downloading file...");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "" + System.currentTimeMillis());
DownloadManager manager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch(requestCode){
case PERMISSION_STORAGE_CODE: {
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
startDownloading();
} else {
Toast.makeText(this, "Permission denied...!", Toast.LENGTH_SHORT).show();
}
}
}
}
}
Manifest.xml permissions
<uses-permission android:name="android.permission.INSTALL_PACKAGES"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS"/>
<uses-permission android:name="android.permission.INTERNET"/>

Related

Getting Cannot load null bitmap when loading images from gallery

I'm trying to load images from Camera and Gallery to load inside Tensor flow lite model.
When loading image from gallery, I'm getting following errors.
2021-01-02 11:48:03.309 9858-9858/com.example.coco_classif E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/Pictures/20200714_135735 (1).jpg: open failed: EACCES (Permission denied)
2021-01-02 11:48:03.332 9858-9858/com.example.coco_classif E/Error log: java.lang.NullPointerException: Cannot load null bitmap.
NOTE: Issues seems coming from the try catch block, loading from camera works fine
mainfest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.coco_classif">
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Coco_classif">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Main Activity
package com.example.coco_classif;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
private static final int CAMERA_PERMISSION_REQUEST_CODE = 1000;
private static final int CAMERA_REQUEST_CODE = 10001;
private ImageView imageView;
private ListView listView;
private ImageClassifier imageClassifier;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inaializeUIElements();
}
private void inaializeUIElements() {
imageView = findViewById(R.id.iv_capture);
listView = findViewById(R.id.lv_probabilities);
Button takepicture = findViewById(R.id.bt_take_picture);
try {
imageClassifier = new ImageClassifier(this);
} catch (IOException e) {
Log.e("Error While Creating Image Classifier", "Error" +e);
}
takepicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(hasPermission()) {
selectImage();
}else{
requestPermission();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Bitmap photo = (Bitmap) Objects.requireNonNull(Objects.requireNonNull(data).getExtras()).get("data");
imageView.setImageBitmap(photo);
List<ImageClassifier.Recognition> predictions = imageClassifier.recognizeImage(photo, 0);
final List<String> predictionList = new ArrayList<>();
for(ImageClassifier.Recognition recog: predictions){
predictionList.add("Label: " + recog.getName() + "Confidence: " + recog.getConfidance());
}
ArrayAdapter<String> predictionsAdapter = new ArrayAdapter<>(
this,R.layout.support_simple_spinner_dropdown_item,predictionList);
listView.setAdapter(predictionsAdapter);
}
else if (requestCode == 2) {
try {
Uri selectedImage = data.getData();
String[] filePath = new String[]{MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from gallery......******************.........", picturePath+"");
Toast.makeText(this,picturePath.toString(),Toast.LENGTH_LONG).show();
imageView.setImageBitmap(thumbnail);
List<ImageClassifier.Recognition> predictions = imageClassifier.recognizeImage(thumbnail, 0);
final List<String> predictionList = new ArrayList<>();
for(ImageClassifier.Recognition recog: predictions){
predictionList.add("Label: " + recog.getName() + "Confidence: " + recog.getConfidance());
}
ArrayAdapter<String> predictionsAdapter = new ArrayAdapter<>(
this,R.layout.support_simple_spinner_dropdown_item,predictionList);
listView.setAdapter(predictionsAdapter);
}catch (Exception e){
Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show();
Log.e("Error log", e.toString());
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(hasAllPermissions(grantResults)){
openCamera();
}else {
requestPermission();
}
}
private boolean hasAllPermissions(int[] grantResults) {
for(int result : grantResults){
if (result == PackageManager.PERMISSION_DENIED)
return false;
}
return true;
}
private void requestPermission() {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
if(shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){
Toast.makeText(this," Permission required",Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST_CODE);
}
}
private void openCamera() {
Intent camerIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camerIntent,CAMERA_REQUEST_CODE);
}
private boolean hasPermission() {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
return checkSelfPermission(Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED;
}
return true;
}
private void selectImage() {
final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent camerIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camerIntent,1);
} else if (options[item].equals("Choose from Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
}
Note: This code snippet worked for only writing a text file and I used this method to solve
open failed: EACCES (Permission denied)
I know your Implementation has to deal with images and that is causing this 2021-01-02 11:48:03.332 9858-9858/com.example.coco_classif E/Error log: java.lang.NullPointerException: Cannot load null bitmap.
Also, check out this Exception 'open failed: EACCES (Permission denied)' on Android
I had the exact same problem, all I did was create a directory and write a text file in it.
Also, it is a good practice to create a new filename for images programmatically, use the Date formatter.
As I can see you are using an alert dialog to select images, I suggest you should not do it that way, alert dialog causes a lot of synchronization problems.
This code is tested on android Q One Plus 6t works fine without any errors.
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try {
File root = new File(String.valueOf(Environment.getExternalStorageDirectory())+"/sysInfoReports");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Check you permissions
: Old storage permissions do not work on Android R.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:ignore="ScopedStorage" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Capture Image From Camera using intent creates empty Image file

I followed this tutorial : https://developer.android.com/training/camera/photobasics .
I had some errors, but I resolved them and the app was working fine.
Once you took a picture, the picture would be saved in under this path :
Android/data/<YourAppPackageName>/files/Pictures.
However, after last OS update I'm getting an empty image file with size 0 B!
How can I solve this issue?
here is my github project : https://github.com/AlineJo/CameraGalleryImage.git
here is my code :
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.cameragalleryimage">
<!--Permission to write to storage-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--Inform google play that your app can take pictures-->
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!-- File provider is a generic way to store image file across different Android SDK, And it enable us to get uri-->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.cameragalleryimage.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/img_file_path"></meta-data>
</provider>
<activity android:name=".activities.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
UploadImageFragment
package com.example.cameragalleryimage.fragments;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import com.example.cameragalleryimage.R;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import static android.app.Activity.RESULT_OK;
/**
* A simple {#link Fragment} subclass.
*/
public class UploadImageFragment extends Fragment implements ChooseDialogFragment.ChooseDialogInterface {
private static final int PICK_IMAGE = 100;
private static final int CAPTURE_IMAGE = 200;
private static final int STORAGE_PERMISSION_REQUEST = 300;
private Context mContext;
private Uri mImageUri;
private ImageView ivImg;
private TextView tvProgress;
private ProgressBar progressBar;
private String mImagePath;
public UploadImageFragment() {
// Required empty public constructor
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
mContext = context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View parentView = inflater.inflate(R.layout.fragment_upload_image, container, false);
ivImg = parentView.findViewById(R.id.iv_img);
tvProgress = parentView.findViewById(R.id.tv_progress);
progressBar = parentView.findViewById(R.id.progressBar);
Button btnChoose = parentView.findViewById(R.id.btn_choose);
Button btnUpload = parentView.findViewById(R.id.btn_upload);
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ChooseDialogFragment dialog = new ChooseDialogFragment();
dialog.setChooseDialogListener(UploadImageFragment.this);
dialog.show(getChildFragmentManager(), ChooseDialogFragment.class.getSimpleName());
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mImageUri == null) {
Toast.makeText(mContext, "Please take an image", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, "Image URI Found : " + mImageUri.toString(), Toast.LENGTH_LONG).show();
}
}
});
return parentView;
}
#Override
public void onGalleryButtonClick() {
Intent i = new Intent();
i.setType("image/*"); // specify the type of data you expect
i.setAction(Intent.ACTION_GET_CONTENT); // we need to get content from another act.
startActivityForResult(Intent.createChooser(i, "choose App"), PICK_IMAGE);
}
#Override
public void onCameraButtonClick() {
if (isPermissionGranted()) {
openCamera();
} else {
showRunTimePermission();
}
}
private void openCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(mContext.getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.d("capture_error", ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
mImageUri = FileProvider.getUriForFile(mContext,
"com.example.cameragalleryimage.fileprovider",
photoFile);
startActivityForResult(takePictureIntent, CAPTURE_IMAGE);
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null) {
if (requestCode == CAPTURE_IMAGE) {//img from camera
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
ivImg.setImageBitmap(imageBitmap);
} else if (requestCode == PICK_IMAGE) {// img from gallery
try {
Uri imgUri = data.getData();
InputStream imageStream = mContext.getContentResolver().openInputStream(imgUri);//2
Bitmap selectedImageBitmap = BitmapFactory.decodeStream(imageStream);//3}
mImageUri = imgUri;
ivImg.setImageBitmap(selectedImageBitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} else {
Toast.makeText(mContext, "Unexpected Error Happened while selecting picture!", Toast.LENGTH_SHORT).show();
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "IMG_" + timeStamp + "_";
File storageDir = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);// mContext.getExternalCacheDir();
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mImagePath = image.getAbsolutePath();
return image;
}
private boolean isPermissionGranted() {
return ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
}
public void showRunTimePermission() {
// Permission is not Granted !
// we should Request the Permission!
// put all permissions you need in this Screen into string array
String[] permissionsArray = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
//here we requet the permission
requestPermissions(permissionsArray, STORAGE_PERMISSION_REQUEST);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// user grants the Permission!
// you can call the function to write/read to storage here!
openCamera();
} else {
// user didn't grant the Permission we need
Toast.makeText(mContext, "Please Grant the Permission To use this Feature!", Toast.LENGTH_LONG).show();
}
}
}
img_file_path.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-files-path
name="my_images"
path="/" />
<!-- Android/data/com.example.cameragalleryimage/files/Pictures-->
</paths>
Super thanks to #CommonsWare and #blackapps comments I was able to get uri and display the captured image
You can find the updated GitHub project here: https://github.com/AlineJo/CameraGalleryImage.git
here is the code I changed :
package com.example.cameragalleryimage.fragments;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import com.bumptech.glide.Glide;
import com.example.cameragalleryimage.R;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import static android.app.Activity.RESULT_OK;
/**
* A simple {#link Fragment} subclass.
*/
public class UploadImageFragment extends Fragment implements ChooseDialogFragment.ChooseDialogInterface {
private static final int PICK_IMAGE = 100;
private static final int CAPTURE_IMAGE = 200;
private static final int STORAGE_PERMISSION_REQUEST = 300;
private Context mContext;
private Uri mImageUri;
private ImageView ivImg;
private TextView tvProgress;
private ProgressBar progressBar;
private String mImagePath;
private File photoFile;
public UploadImageFragment() {
// Required empty public constructor
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
mContext = context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View parentView = inflater.inflate(R.layout.fragment_upload_image, container, false);
ivImg = parentView.findViewById(R.id.iv_img);
tvProgress = parentView.findViewById(R.id.tv_progress);
progressBar = parentView.findViewById(R.id.progressBar);
Button btnChoose = parentView.findViewById(R.id.btn_choose);
Button btnUpload = parentView.findViewById(R.id.btn_upload);
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ChooseDialogFragment dialog = new ChooseDialogFragment();
dialog.setChooseDialogListener(UploadImageFragment.this);
dialog.show(getChildFragmentManager(), ChooseDialogFragment.class.getSimpleName());
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mImageUri == null) {
Toast.makeText(mContext, "Please take an image", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(mContext, "Image URI Found : " + mImageUri.toString(), Toast.LENGTH_LONG).show();
}
}
});
return parentView;
}
#Override
public void onGalleryButtonClick() {
Intent i = new Intent();
i.setType("image/*"); // specify the type of data you expect
i.setAction(Intent.ACTION_GET_CONTENT); // we need to get content from another act.
startActivityForResult(Intent.createChooser(i, "choose App"), PICK_IMAGE);
}
#Override
public void onCameraButtonClick() {
if (isPermissionGranted()) {
openCamera();
} else {
showRunTimePermission();
}
}
private void openCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(mContext.getPackageManager()) != null) {
// Create the File where the photo should go
photoFile = null;
try {
photoFile = createFileInstance();
} catch (IOException ex) {
// Error occurred while creating the File
Log.d("capture_error", ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
mImageUri = FileProvider.getUriForFile(mContext,
"com.example.cameragalleryimage.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri); //this code was messing, However adding this code will make "Intent data" (in "onActivityResult") to be null
Glide.with(mContext).load(mImageUri).into(ivImg);//solution ask glide to load the image using uri
startActivityForResult(takePictureIntent, CAPTURE_IMAGE);
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null) {
if (requestCode == PICK_IMAGE) {// img from gallery
try {
Uri imgUri = data.getData();
InputStream imageStream = mContext.getContentResolver().openInputStream(imgUri);//2
Bitmap selectedImageBitmap = BitmapFactory.decodeStream(imageStream);//3}
mImageUri = imgUri;
ivImg.setImageBitmap(selectedImageBitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} else {
if (requestCode == CAPTURE_IMAGE) {
if (photoFile.length() == 0) {
Toast.makeText(mContext, "You took an image, but you canceled it!", Toast.LENGTH_SHORT).show();
mImageUri = null;
}
}
}
}
private File createFileInstance() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "IMG_" + timeStamp + "_";
File storageDir = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);// mContext.getExternalCacheDir();
File image = new File(storageDir.toString()+"/"+imageFileName+".png");
// Save a file: path for use with ACTION_VIEW intents
mImagePath = image.getAbsolutePath();
return image;
}
private boolean isPermissionGranted() {
return ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
}
public void showRunTimePermission() {
// Permission is not Granted !
// we should Request the Permission!
// put all permissions you need in this Screen into string array
String[] permissionsArray = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
//here we requet the permission
requestPermissions(permissionsArray, STORAGE_PERMISSION_REQUEST);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// user grants the Permission!
// you can call the function to write/read to storage here!
openCamera();
} else {
// user didn't grant the Permission we need
Toast.makeText(mContext, "Please Grant the Permission To use this Feature!", Toast.LENGTH_LONG).show();
}
}
}
If you are updated to Android10. Then use below code snippet.
<application android:requestLegacyExternalStorage="true" ... >
...
</application>

Trying To get text file from storage in Android Studio [duplicate]

This question already has answers here:
Create a file from a photo URI on Android
(1 answer)
Android - Get real path of a .txt file selected from the file explorer
(1 answer)
Closed 3 years ago.
I'm trying to get text file from the storage.
Here is my code. It is catching IOexception, why?
I had created a button which lets me choose the text file but as soon as click on the
file it does give me any path TOAST and it does not send the text to my text view.
Here is my code below:
package com.example.filechooser2;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.BufferUnderflowException;
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_STORAGE = 1000;
private static final int READ_REQUEST_CODE =400 ;
Button b_load;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b_load = (Button) findViewById(R.id.b_load);
tv = (TextView) findViewById(R.id.tv);
b_load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
performFileSearch();
}
});
//requesting permission
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},PERMISSION_REQUEST_STORAGE);
}
}
This is where the code creates problem i think because
it shows the Exception error , please help
// Reading Content
private String readText(String input)
{
File file = new File(Environment.getExternalStorageDirectory(),input);
StringBuilder text = new StringBuilder();
try{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while((line = br.readLine()) != null)
{
text.append(line);
text.append("\n");
} br.close();
}
catch (IOException e){
e.printStackTrace();
Toast.makeText(this,"Messed up",Toast.LENGTH_SHORT).show();
}
return text.toString();
}
// NOW TO GET FROM FILE SYSTEM
private void performFileSearch()
{
Intent i = new Intent (Intent.ACTION_OPEN_DOCUMENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("text/*");
startActivityForResult(i,READ_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data)
{
if(requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK);
{
if(data != null)
{
Uri uri = data.getData();
String Path = uri.getPath();
Path = Path.substring(Path.indexOf(":")+1);
if(Path.contains("emulated"))
{
Path = Path.substring(Path.indexOf("0")+1);
}
Toast.makeText(this,""+Path,Toast.LENGTH_SHORT);
tv.setText(readText(Path));
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode==PERMISSION_REQUEST_STORAGE){
if (grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this,"Permisssion Granted",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this,"Permission Not Given",Toast.LENGTH_SHORT).show();
finish();
}
}
}
}

App for downloading and displaying a pdf within app just returns blank content

I searched the web for examples displaying pdf documents within a app. Additionally i searched for a Downloader class because i want to load the pdf from the internet. After execution it just displays blank PDF page.
MainActivity.java just sends the pdf link to the DisplayPDF.java Activity:
package com.example.pdfviewevaluation;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "com.example.pdfviewevaluation.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, DisplayPDF.class);
String url = "pdf link";
intent.putExtra(EXTRA_MESSAGE, url);
startActivity(intent);
}
}
DisplayPDF.java creates the Folder and PDF in the cache directory. Then it starts the Downloader with the pdf link and directory. Finally it should just show the pdf:
package com.example.pdfviewevaluation;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class DisplayPDF extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_pdf);
String pdfURL = getIntent().getStringExtra(MainActivity.EXTRA_MESSAGE);
File folder = new File(this.getCacheDir(), "pdf");
folder.mkdir();
File file = new File(folder, "Read.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader dl = new Downloader(pdfURL, file);
try {
dl.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
showPdf();
}
public void showPdf() {
File file = new File(this.getCacheDir()+"/pdf/Read.pdf");
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = FileProvider.getUriForFile(this.getApplicationContext(), this.getApplicationContext().getPackageName() + ".provider", file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}
}
Downloader.java connects to the pdf page and download the pdf from the given link to the desired directory:
package com.example.pdfviewevaluation;
import android.os.AsyncTask;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Downloader extends AsyncTask<Void,Void,Void> {
private String fileURL;
private File directory;
public Downloader(String fileURL, File directory)
{
this.fileURL = fileURL;
this.directory = directory;
}
protected Void doInBackground(Void... params) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
int i = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
After many hours spending on my problem i searched for another solution on YouTube. These one are showing the solution:
https://www.youtube.com/watch?v=pGlqHeB5hdk
https://www.youtube.com/watch?v=8YPJCOxiklQ
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.downloadingfiles">
<uses-sdk android:minSdkVersion="21"
android:targetSdkVersion="22" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java:
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.pdf.PdfRenderer;
import android.net.Uri;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.webkit.URLUtil;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
String myUrl = "http://www.orimi.com/pdf-test.pdf";
private ImageView imageView;
private int currentPage = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myUrl));
request.setTitle("File download.");
request.setDescription("File is being downloaded...");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
String nameOfFile = URLUtil.guessFileName(myUrl, null, MimeTypeMap.getFileExtensionFromUrl(myUrl));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, nameOfFile);
DownloadManager manager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
BroadcastReceiver onComplete=new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
render();
}
};
/**Called when the user clicks the "Next" button defined in activity_main.xml */
public void nextPage(View view) {
currentPage++;
render();
}
/**Called when the user clicks the "Previous" button defined in activity_main.xml */
public void previousPage(View view) {
currentPage--;
render();
}
private void render(){
try{
imageView = (ImageView) findViewById(R.id.image);
int REQ_WIDTH = imageView.getWidth();
int REQ_HEIGHT = imageView.getHeight();
Bitmap bitmap = Bitmap.createBitmap(REQ_WIDTH, REQ_HEIGHT, Bitmap.Config.ARGB_4444);
String nameOfFile = URLUtil.guessFileName(myUrl, null, MimeTypeMap.getFileExtensionFromUrl(myUrl));
File file = new File("/sdcard/Download/"+nameOfFile);
PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));
if(currentPage < 0){
currentPage = 0;
}else if(currentPage >= renderer.getPageCount()){
currentPage = renderer.getPageCount() - 1;
}
Matrix m = imageView.getImageMatrix();
Rect rect = new Rect(0, 0, REQ_WIDTH, REQ_HEIGHT);
renderer.openPage(currentPage).render(bitmap, rect, m, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
imageView.setImageMatrix(m);
imageView.setImageBitmap(bitmap);
imageView.invalidate();
} catch (Exception e){
e.printStackTrace();
}
}
}

Android WiFi Direct - client/server - ECONNREFUSED (Connection refused) UPDATE

I have a problem with my Android client/server app. I would like to connect devices by WiFi Direct and send through some media files.
I made an Activity and Service for both Client and Server. Code is below.
ServerActivity:
import java.util.ArrayList;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ServerActivity extends Activity {
private WifiP2pManager wifiManager;
private Channel wifichannel;
private BroadcastReceiver wifiServerReceiver;
private IntentFilter wifiServerReceiverIntentFilter;
private WifiP2pConfig config;
private String deviceName;
private Intent intent;
PeerListListener myPeerListListener;
ArrayList<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
WifiP2pDeviceList peerList;
TextView text;
EditText et2;
Button button1;
ListView listView;
ArrayAdapter<String> BTArrayAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.server_activity);
// Block auto opening keyboard
this.getWindow()
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(BTArrayAdapter);
wifiManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
wifichannel = wifiManager.initialize(this, getMainLooper(), null);
wifiServerReceiverIntentFilter = new IntentFilter();
;
wifiServerReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
wifiServerReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
wifiServerReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
wifiServerReceiverIntentFilter
.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
intent = null;
registerReceiver(wifiServerReceiver, wifiServerReceiverIntentFilter);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
wifiManager.discoverPeers(wifichannel, null);
wifiManager.requestPeers(wifichannel, new PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
peers.clear();
peers.addAll(peerList.getDeviceList());
}
});
for (int i = 0; i < peers.size(); i++) {
WifiP2pDevice device = peers.get(i);
deviceName = device.deviceName;
config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
config.wps.setup = WpsInfo.PBC;
wifiManager.connect(wifichannel, config, new ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(
getApplicationContext(),
"Połączono z: " + deviceName + "\n Mac: "
+ config.deviceAddress, Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reason) {
Toast.makeText(getApplicationContext(), "Nie udało się połączyć",
Toast.LENGTH_SHORT).show();
}
});
}
wifiManager.requestConnectionInfo(wifichannel,
new WifiP2pManager.ConnectionInfoListener() {
#Override
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
// TODO Auto-generated method stub
String groupOwnerAddress = info.groupOwnerAddress.getHostAddress();
Toast.makeText(getApplicationContext(),
"GroupOwnAddress: " + groupOwnerAddress, Toast.LENGTH_SHORT)
.show();
}
});
StartServer(null);
}
});
}
public void StartServer(View v) {
// Construct our Intent specifying the Service
intent = new Intent(this, ServerService.class);
startService(intent);
}
}
ServerService:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.widget.Toast;
public class ServerService extends IntentService {
Handler mHandler;
private int port = 2178;
ServerSocket welcomeSocket = null;
Socket socket = null;
public ServerService() {
super("ServerService");
mHandler = new Handler();
}
#Override
protected void onHandleIntent(Intent intent) {
try {
mHandler.post(new DisplayToast(this, "Creating ServerSocket.."));
welcomeSocket = new ServerSocket(port);
welcomeSocket.setReuseAddress(true);
mHandler.post(new DisplayToast(this, "Waiting for connection on port: "
+ welcomeSocket.getLocalPort()));
socket = welcomeSocket.accept();
// while(true && flag){
// socket = welcomeSocket.accept();
mHandler.post(new DisplayToast(this, "Coneccted!"));
// }
mHandler.post(new DisplayToast(this, "Succes!"));
} catch (IOException e) {
mHandler.post(new DisplayToast(this, "IOException"));
} catch (Exception e) {
mHandler.post(new DisplayToast(this, "Exception"));
}
mHandler.post(new DisplayToast(this, "ServerService"));
}
/*
public void onDestroy() {
try {
welcomeSocket.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stopSelf();
}*/
}
class DisplayToast2 implements Runnable {
private final Context mContext;
String mText;
public DisplayToast2(Context mContext, String text) {
this.mContext = mContext;
mText = text;
}
public void run() {
Toast.makeText(mContext, mText, Toast.LENGTH_SHORT).show();
}
}
ClientActivity:
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
public class ClientActivity extends Activity {
Button button;
private WifiP2pManager wifiManager;
private Channel wifichannel;
private BroadcastReceiver wifiClientReceiver;
private IntentFilter wifiClientReceiverIntentFilter;
private WifiP2pInfo wifiInfo;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client_activity);
// Block auto opening keyboard
this.getWindow()
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
wifiManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
wifichannel = wifiManager.initialize(this, getMainLooper(), null);
wifiClientReceiver = new WiFiClientBroadcastReceiver(wifiManager, wifichannel, this);
wifiClientReceiverIntentFilter = new IntentFilter();
;
wifiClientReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
wifiClientReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
wifiClientReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
wifiClientReceiverIntentFilter
.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
wifiInfo = null;
registerReceiver(wifiClientReceiver, wifiClientReceiverIntentFilter);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
StartClient(null);
}
});
}
public void setNetworkToReadyState(boolean status, WifiP2pInfo info, WifiP2pDevice device) {
wifiInfo = info;
// targetDevice = device;
// connectedAndReadyToSendFile = status;
}
public void StartClient(View v) {
Intent intent = new Intent(this, ClientService.class);
intent.putExtra("wifiInfo", wifiInfo);
if (wifiInfo == null) {
Toast.makeText(this, "WifiInfo = null!", Toast.LENGTH_SHORT).show();
}
startService(intent);
}
}
ClientService:
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.p2p.WifiP2pInfo;
import android.os.Handler;
import android.widget.Toast;
public class ClientService extends IntentService {
Handler mHandler;
private WifiP2pInfo wifiInfo;
private int port = 2178;
Socket clientSocket = null;
OutputStream os = null;
public ClientService() {
super("ClientService");
mHandler = new Handler();
}
#Override
protected void onHandleIntent(Intent intent) {
wifiInfo = (WifiP2pInfo) intent.getExtras().get("wifiInfo");
InetAddress targetIP = wifiInfo.groupOwnerAddress;
clientSocket = new Socket();
if(wifiInfo.isGroupOwner)
{
try {
mHandler.post(new DisplayToast(this, "Try to connect: /N IP: " + targetIP + "/nPort: " +port));
clientSocket.connect(new InetSocketAddress(targetIP, port));
mHandler.post(new DisplayToast(this, "Connected!"));
//os = clientSocket.getOutputStream();
} catch (IOException e) {
mHandler.post(new DisplayToast(this, "serwer IOException: " + e.getMessage()));
} catch (Exception e) {
mHandler.post(new DisplayToast(this, "serwer Exception"));
}
}else{
mHandler.post(new DisplayToast(this, "Group owner = " + wifiInfo.isGroupOwner));
}
}
/*
public void onDestroy()
{
try {
os.close();
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stopSelf();
}*/
}
class DisplayToast implements Runnable {
private final Context mContext;
String mText;
public DisplayToast(Context mContext, String text) {
this.mContext = mContext;
mText = text;
}
public void run() {
Toast.makeText(mContext, mText, Toast.LENGTH_SHORT).show();
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".AppModeSelection"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".ServerService"
android:exported="false" />
<service
android:name=".ClientService"
android:exported="false" />
<activity android:name=".ServerActivity" >
</activity>
<activity android:name=".ClientActivity" >
</activity>
</application>
</manifest>
I am using two phones with WiFi Direct (Samsung GT-I9505 Android 4.4.2 and Samsung GT-I8190N Adroid 4.1.2). First of all I turned off all connections (BT, WIFI) and then connected by WiFi Direct. GT-I9505 is Server and other one is Client. While establishing a connection IOException error appears:
IOException: failed to connect to /192.168.49.1 (port 2178): connect failed: ECONNREFUSED (Connection refused)
I tried to use plenty of others Pors but nothing works. What I did wrong?
Thank you in advance for any help!
UPDATE:
I noticed that when I disconnect WiFi direct and connect again but in other direction it works but only for moment.
the main issue with your code is that you do need to make it event driven, in the current state I'm surprised that it even does anything really.
So, please try making it to something like following:
1. Start Discovering peers, once you get Peers Changed event, then do requestPeers
2. if you need some listener etc. to be ready for you on the other side, then you likely would identify those devices by advertising a service, so next look start discovery for services.
3. After you get service discovered, start 5-second timer to wait for any additional, reset the timer after each service discovered, and once the timer finally gets to run uninterrupted 5 seconds, you likely have discovered all services available at that time.
4. Select ONE service and connect to that device (you can not have multiple connection really).
5. Once you get event that you are connected, then use requestConnectionInfo to get info for the connection.
Then do remember that before you start you need to create the local service, so the other side can see it. Then, if your device gets selected as Group owner, you could keep the advertisement on, and let more clients connect to you. But if you are selected as Client, then you can not have incoming connections, so you should get rid of the advertisement.

Categories

Resources