Hello sackoverflow I'm trying to develop an application which can backup and restore contacts, my code is as follows
public class MainActivity extends Activity
{
Cursor cursor;
ArrayList<String> vCard ;
String vfile;
FileOutputStream mFileOutputStream = null;
Button btnRestorects = null;
Button btnBackupCts = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRestorects = (Button) findViewById(R.id.buttonRstCts);
btnBackupCts = (Button) findViewById(R.id.buttonBackCts);
vfile = "contacts.vcf";
final String storage_path = Environment.getExternalStorageDirectory().toString() +"/"+ vfile;
final File f = new File(storage_path);
btnBackupCts.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
try
{
if (!f.exists())
f.createNewFile();
mFileOutputStream = new FileOutputStream(storage_path, false);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
getVcardString();
}
});
btnRestorects.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
final Intent intent = new Intent();
final MimeTypeMap mime = MimeTypeMap.getSingleton();
String tmptype = mime.getMimeTypeFromExtension("vcf");
final File file = new File(Environment.getExternalStorageDirectory().toString() +"/contacts.vcf");
intent.setDataAndType(Uri.fromFile(file),tmptype);
startActivity(intent);
}
});
}
private void getVcardString()
{
// TODO Auto-generated method stub
vCard = new ArrayList<String>();
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if(cursor!=null&&cursor.getCount()>0)
{
cursor.moveToFirst();
for(int i =0;i<cursor.getCount();i++)
{
get(cursor);
Log.d("TAG", "Contact "+(i+1)+"VcF String is"+vCard.get(i));
cursor.moveToNext();
}
}
else
{
Log.d("TAG", "No Contacts in Your Phone");
}
try
{
mFileOutputStream.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void get(Cursor cursor)
{
//cursor.moveToFirst();
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try
{
fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String vcardstring= new String(buf);
vCard.add(vcardstring);
mFileOutputStream.write(vcardstring.toString().getBytes());
}
catch (Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
Permissions in manifest
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
So far my code was backing up the contact but only name and contact number, but not retrieving the information like whether the contact is starred or not. Please help me in solving this riddle.
Thanks in advance.
Use this to restore:
final MimeTypeMap mime = MimeTypeMap.getSingleton();
String tmptype = mime.getMimeTypeFromExtension("vcf");
final File file = new File(Environment.getExternalStorageDirectory().toString()
+ "/contacts.vcf");
Intent i = new Intent();
i.setAction(android.content.Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(file), "text/x-vcard");
startActivity(i);
Intent mIntent = new Intent(Intent.ACTION_VIEW);
mIntent.setDataAndType(Uri.fromFile(new File(filePath)), MimeTypeMap.getSingleton().getMimeTypeFromExtension("vcf"));
startActivity(Intent.createChooser(mIntent, "Select App"));
Related
After lots of search i found the full path of the file but while converting it into binary FileNotFoundException' occurred Please Help Guys.
my Codes are
1.
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
/*
* Intent intent = new Intent(); intent.setType("/*");
* intent.setAction(Intent.ACTION_GET_CONTENT);
* startActivityForResult(intent, 33);
*/
Intent intent = new Intent();
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Set your required file type
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "DEMO"),
1001);
}
});
2.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
String displayName = null;
byte[] bytes = null;
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
String uriString = uri.toString();
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = this.getContentResolver().query(uri, null, null,
null, null);
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor
.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
}
String Str = new String(path);
int endPortal=Str.indexOf("document/");
String fullpath=Str.substring(0,endPortal)+"document/"+displayName;
try {
bytes=CommonHelper.getGalleryDetails(fullpath); } catch
(FileNotFoundException e) { // TODO Auto-generated catch block
e.printStackTrace(); } Log.e("fileBinary:", bytes.toString());
Toast.makeText(getBaseContext(), "Binary" + bytes.toString(), 5000).show();
}
}
//I am Getting error on FilePath
//CommonHelper class where getGalleryDetails are written
3.
public static byte[] getGalleryDetails(String FilePath)
throws FileNotFoundException {
InputStream inputStream = null;
byte[] bytes = null;
try {
inputStream = new FileInputStream(FilePath);
byte[] buffer = new byte[2048];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
output.close();
} catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
Log.e("byte", bytes.toString());
output = null;
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return bytes;
}
Please see the above logcate link in title please help me ...thanks in advance
This is the utils code, the MP3 work only when the app is open, once you click in the back or the home button it stops.
How can I put it in the background?
public class Util {
public ArrayList<Contact> getAllContact(Context context) {
ArrayList<Contact> contacts = new ArrayList<Contact>();
Cursor cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME);
if(cursor != null) {
while (cursor.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String aaaa = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.CUSTOM_RINGTONE));
if (phone!=null && phone.equals("1")) {
Contact contact = new Contact();
contact.setId(Integer.parseInt(id));
contact.setName(name);
contacts.add(contact);
}
}
}
cursor.close();
return contacts;
}
public ArrayList<SongInfo> getAllSong(Context context) {
ArrayList<SongInfo> listSong = new ArrayList<SongInfo>();
RingtonesSharedPreferences pref = new RingtonesSharedPreferences(
context);
Field[] fields = R.raw.class.getFields();
for (int i = 0; i < fields.length - 1; i++) {
SongInfo info = new SongInfo();
try {
String name = fields[i].getName();
if (!name.equals("ringtones")) {
info.setFileName(name + ".mp3");
info.setFavorite(pref.getString(info.getFileName()));
int audioResource = R.raw.class.getField(name).getInt(name);
info.setAudioResource(audioResource);
}
// info.setName(name);
} catch (Exception e) {
// TODO: handle exception
// Log.e("LOG", "Error: " + e.getMessage());
}
listSong.add(info);
}
InputStream inputStream = context.getResources().openRawResource(
R.raw.zeallist);
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
try {
String line;
int i = 0;
while ((line = reader.readLine()) != null) {
listSong.get(i).setName(line);
i++;
}
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return listSong;
}
public void assignRingtoneToContact(Context context, SongInfo info,Contact contact) {
File dir =null;
ContentValues values = new ContentValues();
boolean isRingTone = false;
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),
"Ringtones");
} else {
dir = context.getCacheDir();
}
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, info.getFileName());
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
InputStream inputStream = context.getResources()
.openRawResource(info.getAudioResource());
OutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
String[] columns = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.IS_RINGTONE
};
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, MediaStore.Audio.Media.DATA+" = '"+file.getAbsolutePath()+"'",null, null);
if (cursor!=null) {
int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
int fileColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
int ringtoneColumn = cursor.getColumnIndex(MediaStore.Audio.Media.IS_RINGTONE);
while (cursor.moveToNext()) {
String audioFilePath = cursor.getString(fileColumn);
if (cursor.getString(ringtoneColumn)!=null && cursor.getString(ringtoneColumn).equals("1")) {
Uri hasUri = MediaStore.Audio.Media.getContentUriForPath(audioFilePath);
Uri fullUri = Uri.withAppendedPath(hasUri, cursor.getString(idColumn));
isRingTone = true;
values.put(ContactsContract.Contacts.CUSTOM_RINGTONE, fullUri.toString());
}
}
cursor.close();
if(!isRingTone){
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
Uri oldUri = MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath());
ContentValues Newvalues = new ContentValues();
Uri newUri;
String uriString;
context.getContentResolver().delete(oldUri, MediaStore.MediaColumns.DATA + "=\"" + file.getAbsolutePath() + "\"", null);
Newvalues.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
Newvalues.put(MediaStore.MediaColumns.TITLE, info.getName());
Newvalues.put(MediaStore.MediaColumns.SIZE, file.length());
Newvalues.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
Newvalues.put(MediaStore.Audio.Media.IS_RINGTONE, true);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath());
newUri = context.getContentResolver().insert(uri, Newvalues);
uriString = newUri.toString();
values.put(ContactsContract.Contacts.CUSTOM_RINGTONE, uriString);
Log.i("LOG", "uriString: " + uriString);
}
}
int count = context.getContentResolver().update(ContactsContract.Contacts.CONTENT_URI, values,ContactsContract.Contacts._ID +" = "+contact.getId(), null);
// Log.i("LOG", "Update: " + count);
}
#SuppressWarnings("deprecation")
public Uri getContactContentUri() {
if(Build.VERSION.SDK_INT >= 5){
return ContactsContract.Contacts.CONTENT_URI;
}
else{
return Contacts.People.CONTENT_URI;
}
}
}
try using MediaPlayer, it has many options
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(context, ringtone);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
mediaPlayer.start();
You need to develop player as a service, refer this ,
official docs
I am made an android application which get contacts from vcf file and save to android device and the code is:
String tmptype = mime.getMimeTypeFromExtension("vcf");
final File file = new File(Environment.getExternalStorageDirectory().toString() + "/contacts.vcf");
Intent i = new Intent();
i.setDataAndType(Uri.fromFile(file), "text/x-vcard");
startActivity(i);
It saves all contacts into device
but problem is it wants userinterface to choose where to save.But I want directly save to PhoneMemory or Phonebook.I don't want any other option while inserting Contacts.I have search on web could not find any answer please help to find out this
public class VCardActivity extends Activity {
Cursor cursor;
ArrayList<String> vCard;
String vfile;
static Context mContext;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = VCardActivity.this;
getVCF();
}
public static void getVCF() {
final String vfile = "Contacts.vcf";
Cursor phones = mContext.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
phones.moveToFirst();
for (int i = 0; i < phones.getCount(); i++) {
String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try {
fd = mContext.getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String VCard = new String(buf);
String path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(path, true);
mFileOutputStream.write(VCard.toString().getBytes());
phones.moveToNext();
Log.d("Vcard", VCard);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
Add on Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Credit to: https://stackoverflow.com/a/12048639/2378691
I have developed video recording application using Intent.
It creates file and stores at specified location but shows 0 bytes on sdcard.
what would be the problem?
I am setting the path for storing the video at different place on sdcard
Thank you.
public class RecordVideoActivity extends Activity{
Button btn_NewVideoRec;
Button btn_RecVideoList;
ListView lstvwVideo;
VideoView videoview;
final static int REQUEST_VIDEO_CAPTURED = 1;
Uri uriVideo = null;
Uri custLoc;
File myRecFile;
String pathtovideo;
ArrayAdapter<String> videoadap;
ArrayList<String> videolist;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.video_record_activity);
btn_NewVideoRec = (Button)findViewById(R.id.btn_RecordNewVideo);
btn_RecVideoList = (Button)findViewById(R.id.btn_RecordedVideoList);
lstvwVideo = (ListView)findViewById(R.id.videolistview);
videoview = (VideoView)findViewById(R.id.videoVw);
btn_NewVideoRec.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
Uri custLoc = getOutputVideoFileUri();
//intent.putExtra(MediaStore.EXTRA_OUTPUT, custLoc);
startActivityForResult(intent, REQUEST_VIDEO_CAPTURED);
}
});
btn_RecVideoList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
System.out.println("path to video::"+pathtovideo);
int lstindxofslash = pathtovideo.lastIndexOf("/");
System.out.println("last index of slash::"+lstindxofslash);
String pathofvdofldr = pathtovideo.substring(0,lstindxofslash);
System.out.println("path of video folder:"+pathofvdofldr);
File srcDir = new File(pathofvdofldr);
File dstDir = new File(Environment.getExternalStorageDirectory()+"/app");
}catch (NullPointerException e) {
// TODO: handle exception
e.getStackTrace();
}
ListView videolw = (ListView)findViewById(R.id.videolistview);
videolw.setVisibility(View.VISIBLE);
videolist = getRecVideoFiles(Environment.getExternalStorageDirectory()+"/app/video");
//videolist = getRecVideoFiles(Environment.getExternalStorageDirectory()+"/DCIM/Camera");
//"Whatsapp/Media/WhatsApp Video/");
videoadap = new ArrayAdapter<String>(RecordVideoActivity.this, android.R.layout.simple_list_item_1, videolist);
videolw.setAdapter(videoadap);
videolw.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), videolist.get(pos), Toast.LENGTH_SHORT).show();
videoview.setVisibility(View.VISIBLE);
btn_NewVideoRec.setVisibility(View.GONE);
btn_RecVideoList.setVisibility(View.GONE);
lstvwVideo.setVisibility(View.GONE);
MediaController mediaController = new MediaController(RecordVideoActivity.this);
mediaController.setAnchorView(videoview);
// Set video link (mp4 format )
Uri video = Uri.parse(videolist.get(pos));
videoview.setMediaController(mediaController);
videoview.setVideoURI(video);
videoview.start();
}
});
}
});
}
public Uri getOutputVideoFileUri(){
return Uri.fromFile(getOutPutVideoFile());
}
public File getOutPutVideoFile(){
String videofolder = "/app/video";
File videofldr = new File(Environment.getExternalStorageDirectory().toString()+videofolder);
if (videofldr.isDirectory()) {
myRecFile = new File(videofldr.getAbsolutePath()+"/"+System.currentTimeMillis()+".mp4");
//myRecFile = audiofldr.toString()+"/"+System.currentTimeMillis()+".3gp";
System.out.println("Path for existing folder::"+myRecFile);
} else {
videofldr.mkdir();
System.out.println("path for created directory::"+myRecFile.getAbsolutePath());
myRecFile = new File(videofldr.getAbsolutePath()+"/"+System.currentTimeMillis()+".mp4");
}
return myRecFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if(requestCode == REQUEST_VIDEO_CAPTURED){
//pathtovideo = getpathofVideo(data.getData());
//System.out.println("pathv::"+pathtovideo);
uriVideo = data.getData();
//uriVideo = (Uri) data.getExtras().get(custLoc.toString());
Toast.makeText(RecordVideoActivity.this,uriVideo.getPath(),Toast.LENGTH_LONG).show();
System.out.println("UriVideoPath::"+uriVideo.getPath());
}
}else if(resultCode == RESULT_CANCELED){
uriVideo = null;
Toast.makeText(RecordVideoActivity.this, "Cancelled!",Toast.LENGTH_LONG).show();
}
}
}
private String getpathofVideo(Uri uriVideo) {
// TODO Auto-generated method stub
String[] proj = { MediaStore.Video.Media.DATA };
Cursor cursor = managedQuery(uriVideo, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private ArrayList<String> getRecVideoFiles(String videorecpath) {
// TODO Auto-generated method stub
ArrayList<String> videofiles = new ArrayList<String>();
File file = new File(videorecpath);
file.mkdir();
File[] f = file.listFiles();
if (f.length == 0) {
Toast.makeText(getApplicationContext(), "No Files!", Toast.LENGTH_SHORT).show();
}else{
for (int i = 0; i < f.length; i++) {
System.out.println("from file.."+f[i].toString());
videofiles.add(f[i].getName());
System.out.println("from arraylist.."+videofiles.get(i).toString());
}
}
return videofiles;
}
}
Instead of your code Try this: First record video aftr that get data and write it to particular location.
Intent photoPickerIntent= new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(Intent.createChooser(photoPickerIntent,"Take Video"),TAKE_VIDEO);
And startActivityForResult will be:
try
{
AssetFileDescriptor videoAsset = getContentResolver().openAssetFileDescriptor(data.getData(), "r");
FileInputStream fis = videoAsset.createInputStream();
File root=new File(Environment.getExternalStorageDirectory(),"Directory");
if (!root.exists()) {
root.mkdirs();
}
File file;
file = new File(root,"test.mp4" );
Uri uri=Uri.fromFile(file);
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
I am trying to share my internal storage file via Gmail client on my Moto Razr, but every time I sent to my test gmail account, I got everything except attachment.
This is how I invoke and start gmail, while add file as attachment.
private void saveDaily() {
Intent intent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { loadEmailAddress() });
intent.putExtra(Intent.EXTRA_SUBJECT, "Daily");
intent.putExtra(Intent.EXTRA_TEXT, "Daily Log");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
ArrayList<Uri> uris = new ArrayList<Uri>();
uris.add(saveDaily2File("dailyRecord.txt"));
Log.d(TAG_D, "Size: " + uris.size());
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
startActivity(Intent.createChooser(intent, "Send email"));
}
This is how I implement my customized content provider.
public class SavedFileProvider extends ContentProvider {
private static final String TAG_D = "ContentProvider";
private static final HashMap<String, String> MIME_TYPES = new HashMap<String, String>();
static {
MIME_TYPES.put(".txt", "text/plain");
}
#Override
public String getType(Uri uri) {
String path = uri.toString();
for (String extension : MIME_TYPES.keySet()) {
if (path.endsWith(extension)) {
return (MIME_TYPES.get(extension));
}
}
return (null);
}
#Override
public ParcelFileDescriptor openFile(Uri uri, String mode)
throws FileNotFoundException {
Log.d(TAG_D, "openFile()");
File f = new File(getContext().getFilesDir(), uri.getPath());
Log.d(TAG_D, f.getAbsolutePath());
if (f.exists()) {
return (ParcelFileDescriptor.open(f,
ParcelFileDescriptor.MODE_READ_ONLY));
}
throw new FileNotFoundException(uri.getPath());
}
#Override
public Cursor query(Uri url, String[] projection, String selection,
String[] selectionArgs, String sort) {
throw new RuntimeException("Operation not supported");
}
#Override
public Uri insert(Uri uri, ContentValues initialValues) {
throw new RuntimeException("Operation not supported");
}
#Override
public int update(Uri uri, ContentValues values, String where,
String[] whereArgs) {
throw new RuntimeException("Operation not supported");
}
#Override
public int delete(Uri uri, String where, String[] whereArgs) {
throw new RuntimeException("Operation not supported");
}
private void copy(InputStream in, File dst) throws IOException {
FileOutputStream out = new FileOutputStream(dst);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
#Override
public boolean onCreate() {
Log.d(TAG_D, "onCreate()");
File f = new File(getContext().getFilesDir(), "dailyRecord.txt");
if (!f.exists()) {
AssetManager assets = getContext().getResources().getAssets();
try {
copy(assets.open("dailyRecord.txt"), f);
} catch (IOException e) {
Log.e("FileProvider", "Exception copying from assets", e);
return (false);
}
}
return (true);
}
}
Then, I add the following lines in my AndroidManifest.xml File.
<provider
android:name=".SavedFileProvider"
android:authorities="Package Path here"
android:exported="true"
android:grantUriPermissions="true"
android:multiprocess="true" >
</provider>
I wonder what I am missing here.
I have check the link:Link1, Link2
I use this:
AndroidManifest.xml
<provider android:name="com.myapp.main.MyContentProvider" android:authorities="com.myapp.main"></provider>
Button click:
public void onClick(View v) {
List<Intent> targetedShareIntents = new ArrayList<Intent>();
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/jpg");
Uri theUri = Uri.parse("content://com.myapp.main/"+srcImage);
List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(shareIntent, 0);
int i=0;
List<ResolveInfo> reInfoToDelete = new ArrayList<ResolveInfo>();
if (!resInfo.isEmpty()){
for (ResolveInfo resolveInfo : resInfo) {
String packageName = resolveInfo.activityInfo.packageName;
Intent targetedShareIntent = new Intent(android.content.Intent.ACTION_SEND);
targetedShareIntent.setType("image/jpg");
targetedShareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Share file");
if (packageName.equals("com.google.android.gm")){
targetedShareIntent.setType("image/png");
targetedShareIntent.putExtra(Intent.EXTRA_TEXT, "some text");
targetedShareIntent.putExtra(Intent.EXTRA_STREAM, theUri);
targetedShareIntent.setPackage(packageName);
targetedShareIntents.add(targetedShareIntent);
}
}
startActivity(targetedShareIntents.remove(0));
}
}
My Content Provider Class
public class MyContentProvider extends ContentProvider implements PipeDataWriter<InputStream>{
#Override
public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
//Adapt this to your code
AssetManager am = getContext().getAssets();
String file_name = "path/"+uri.getLastPathSegment();
if(file_name == null)
throw new FileNotFoundException();
AssetFileDescriptor afd = null;
try {
afd = am.openFd(file_name);
} catch (IOException e) {
e.printStackTrace();
}
return afd;//super.openAssetFile(uri, mode);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
#Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
return null;
}
#Override
public boolean onCreate() {
// TODO Auto-generated method stub
return false;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// TODO Auto-generated method stub
return null;
}
#Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
public void writeDataToPipe(ParcelFileDescriptor arg0, Uri arg1,
String arg2, Bundle arg3, InputStream arg4) {
// Transfer data from the asset to the pipe the client is reading.
byte[] buffer = new byte[8192];
int n;
FileOutputStream fout = new FileOutputStream(arg0.getFileDescriptor());
try {
while ((n=arg4.read(buffer)) >= 0) {
fout.write(buffer, 0, n);
}
} catch (IOException e) {
Log.i("InstallApk", "Failed transferring", e);
} finally {
try {
arg4.close();
} catch (IOException e) {
}
try {
fout.close();
} catch (IOException e) {
}
}
}
}