This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Android App high cpu-usage
I am programming a app that has to do a operation with high cpu usage on a longer time
the operation is startet like a service
but the android system kills the app because of the high cpu usage
so what can I do to reduce the cpu usage ?
and make the system not to stop my service ?
service :
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.IBinder;
import android.provider.ContactsContract;
public class backup_service extends Service {
int i;
int i2;
#Override
public void onCreate() {
try
{
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/dialog.db");
BufferedWriter out = new BufferedWriter(fstream);
out.write("on");
//Close the output stream
out.close();
backup();
}
catch (Exception x)
{
stopSelf();
}
}
#Override
public void onDestroy() {
util.deleteDir(new File("/data/data/contact.backup.alexander.fuchs/dialog.db"));
stopSelf();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void backup()
{
util.deleteDir(new File("/data/data/contact.backup.alexander.fuchs/backup/"));
new File("/data/data/contact.backup.alexander.fuchs/backup/").mkdirs();
// get it
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
i = 0;
i2 = 0;
while (cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// write
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/id.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(id);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/name.txt");
out = new BufferedWriter(fstream);
out.write(name);
//Close the output stream
out.close();
}
catch (Exception x)
{
}
if (Integer.parseInt(cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String number = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/number.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(number);
//Close the output stream
out.close();
}
catch(Exception x)
{
}
}
pCur.close();
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/email.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(email);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/email_type.txt");
out = new BufferedWriter(fstream);
out.write(emailType);
//Close the output stream
out.close();
}
catch(Exception x)
{
}
}
emailCur.close();
String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] noteWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams, null);
if (noteCur.moveToFirst()) {
String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
// write
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/note.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(note);
//Close the output stream
out.close();
}
catch (Exception x)
{
}
}
noteCur.close();
String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] addrWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, null, null, null);
while(addrCur.moveToNext()) {
String poBox = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
String street = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
String city = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
String state = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
String postalCode = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
String country = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
String type = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
// write
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/pobox.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(poBox);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/street.txt");
out = new BufferedWriter(fstream);
out.write(street);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/city.txt");
out = new BufferedWriter(fstream);
out.write(city);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/state.txt");
out = new BufferedWriter(fstream);
out.write(state);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/postalcode.txt");
out = new BufferedWriter(fstream);
out.write(postalCode);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/country.txt");
out = new BufferedWriter(fstream);
out.write(country);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"addres_type.txt");
out = new BufferedWriter(fstream);
out.write(type);
//Close the output stream
out.close();
}
catch (Exception x)
{
}
}
addrCur.close();
String imWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] imWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE};
Cursor imCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, imWhere, imWhereParams, null);
if (imCur.moveToFirst()) {
String imName = imCur.getString(
imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
String imType;
imType = imCur.getString(
imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE));
//write
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/im.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(imName);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/im_type.txt");
out = new BufferedWriter(fstream);
out.write(imType);
//Close the output stream
out.close();
}
catch(Exception x)
{
}
}
imCur.close();
String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (orgCur.moveToFirst()) {
String orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
String company = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
String department = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DEPARTMENT));
//write
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/orgName.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(orgName);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/title.txt");
out = new BufferedWriter(fstream);
out.write(title);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/company.txt");
out = new BufferedWriter(fstream);
out.write(company);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/department.txt");
out = new BufferedWriter(fstream);
out.write(department);
//Close the output stream
out.close();
}
catch(Exception x)
{
}
}
orgCur.close();
}
i++;
}
onDestroy();
}
}
}
You have to perform the long duration tasks like this in background, using a thread or AsyncTask as explained here
Related
I want to add some MMS messages into my device database.
I've the following code but it doesn't work at all. No entry are added into the native app...
public static Uri insert(Context context, String[] to, String subject, Uri messageUri)
{
try
{
Uri destUri = Uri.parse("content://mms/sent");
// Get thread id
Set<String> recipients = new HashSet<String>();
recipients.addAll(Arrays.asList(to));
long thread_id = getOrCreateThreadId(context, recipients);
Log.e(">>>>>>>", "Thread ID is " + thread_id);
// Create a dummy sms
ContentValues dummyValues = new ContentValues();
dummyValues.put("thread_id", thread_id);
dummyValues.put("body", "Dummy SMS body.");
Uri dummySms = context.getContentResolver().insert(Uri.parse("content://sms/sent"), dummyValues);
// Create a new message entry
ContentValues mmsValues = new ContentValues();
mmsValues.put("thread_id", thread_id);
mmsValues.put("date", System.currentTimeMillis()/1000);
mmsValues.put("ct_t", "application/vnd.wap.multipart.related");
mmsValues.put("read", "1");
mmsValues.put("sub", subject);
// Create part
long dummyId = System.currentTimeMillis();
createPart(context, dummyId, imageBytes);
// Insert message
Uri res = context.getContentResolver().insert(destUri, mmsValues);
String messageId = res.getLastPathSegment().trim();
Log.e(">>>>>>>", "Message saved as " + res);
// Update part
ContentValues updateValues = new ContentValues();
updateValues.put("mid", messageId);
Uri updateUri = Uri.parse("content://mms/" + dummyId + "/part");
int mmsPartRows = context.getContentResolver().update(updateUri, updateValues, null, null);
Log.e(">>>>>>>", "Part rows " + mmsPartRows);
// Create addresses
for (String addr : to)
{
ContentValues addrValues = new ContentValues();
addrValues.put("address", addr);
addrValues.put("charset", "106");
addrValues.put("type", 151); // TO
Uri addrUri = Uri.parse("content://mms/"+ messageId +"/addr");
Uri mmsAddrUri = context.getContentResolver().insert(addrUri, addrValues);
Log.e(">>>>>>>", "Addr uri is " + mmsAddrUri.toString());
}
res = Uri.parse(destUri + "/" + messageId);
// Delete dummy sms
context.getContentResolver().delete(dummySms, null, null);
return res;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
private static Uri createPart(Context context, long id, byte[] imageBytes) throws Exception
{
ContentValues mmsPartValue = new ContentValues();
mmsPartValue.put("ct", "image/png");
Uri partUri = Uri.parse("content://mms/" + id + "/part");
Uri res = context.getContentResolver().insert(partUri, mmsPartValue);
Log.e(">>>>>>>", "Part uri is " + res.toString());
// Add data to part
OutputStream os = context.getContentResolver().openOutputStream(res);
ByteArrayInputStream is = new ByteArrayInputStream(imageBytes);
byte[] buffer = new byte[256];
for (int len=0; (len=is.read(buffer)) != -1;)
{
os.write(buffer, 0, len);
}
os.close();
is.close();
return res;
}
private static long getOrCreateThreadId(Context context, String[] numbers)
{
HashSet<String> recipients = new HashSet<String>();
recipients.addAll(Arrays.asList(numbers));
return Telephony.Threads.getOrCreateThreadId(context, recipients);
}
context is my view context
to is a string array containing the addresses (eg. new String[] {"0612345678", "0623456789"})
subject is my MMS subject such as "Sent via MyApp"
messageUri is an Uri pointing to the image I want to send on my SD card.
Am I doing it wrong ?
Finally I found how to do the job !
Here is the code I made.
Tell me if you got some troubles with this.
public static Uri insert(Context context, String[] to, String subject, byte[] imageBytes)
{
try
{
Uri destUri = Uri.parse("content://mms");
// Get thread id
Set<String> recipients = new HashSet<String>();
recipients.addAll(Arrays.asList(to));
long thread_id = getOrCreateThreadId(context, recipients);
Log.e(">>>>>>>", "Thread ID is " + thread_id);
// Create a dummy sms
ContentValues dummyValues = new ContentValues();
dummyValues.put("thread_id", thread_id);
dummyValues.put("body", "Dummy SMS body.");
Uri dummySms = context.getContentResolver().insert(Uri.parse("content://sms/sent"), dummyValues);
// Create a new message entry
long now = System.currentTimeMillis();
ContentValues mmsValues = new ContentValues();
mmsValues.put("thread_id", thread_id);
mmsValues.put("date", now/1000L);
mmsValues.put("msg_box", MESSAGE_TYPE_OUTBOX);
//mmsValues.put("m_id", System.currentTimeMillis());
mmsValues.put("read", 1);
mmsValues.put("sub", subject);
mmsValues.put("sub_cs", 106);
mmsValues.put("ct_t", "application/vnd.wap.multipart.related");
mmsValues.put("exp", imageBytes.length);
mmsValues.put("m_cls", "personal");
mmsValues.put("m_type", 128); // 132 (RETRIEVE CONF) 130 (NOTIF IND) 128 (SEND REQ)
mmsValues.put("v", 19);
mmsValues.put("pri", 129);
mmsValues.put("tr_id", "T"+ Long.toHexString(now));
mmsValues.put("resp_st", 128);
// Insert message
Uri res = context.getContentResolver().insert(destUri, mmsValues);
String messageId = res.getLastPathSegment().trim();
Log.e(">>>>>>>", "Message saved as " + res);
// Create part
createPart(context, messageId, imageBytes);
// Create addresses
for (String addr : to)
{
createAddr(context, messageId, addr);
}
//res = Uri.parse(destUri + "/" + messageId);
// Delete dummy sms
context.getContentResolver().delete(dummySms, null, null);
return res;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
private static Uri createPart(Context context, String id, byte[] imageBytes) throws Exception
{
ContentValues mmsPartValue = new ContentValues();
mmsPartValue.put("mid", id);
mmsPartValue.put("ct", "image/png");
mmsPartValue.put("cid", "<" + System.currentTimeMillis() + ">");
Uri partUri = Uri.parse("content://mms/" + id + "/part");
Uri res = context.getContentResolver().insert(partUri, mmsPartValue);
Log.e(">>>>>>>", "Part uri is " + res.toString());
// Add data to part
OutputStream os = context.getContentResolver().openOutputStream(res);
ByteArrayInputStream is = new ByteArrayInputStream(imageBytes);
byte[] buffer = new byte[256];
for (int len=0; (len=is.read(buffer)) != -1;)
{
os.write(buffer, 0, len);
}
os.close();
is.close();
return res;
}
private static Uri createAddr(Context context, String id, String addr) throws Exception
{
ContentValues addrValues = new ContentValues();
addrValues.put("address", addr);
addrValues.put("charset", "106");
addrValues.put("type", 151); // TO
Uri addrUri = Uri.parse("content://mms/"+ id +"/addr");
Uri res = context.getContentResolver().insert(addrUri, addrValues);
Log.e(">>>>>>>", "Addr uri is " + res.toString());
return res;
}
In my application, a number of contacts are attached to single .vcf file and that file sent to mail, try to this one all contacts data display in log cat, but unable to send all data attached to single .vcf file?
Anyone have an idea regarding this help me, please.
here is my code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
vCard = new ArrayList<String>();
Log.i("TAG one", "vfile" +vfile);
vfile = "Contacts" + "_" + System.currentTimeMillis() + ".vcf";
/**
* This Function For Vcard And here i take one Array List in Which i
* store every Vcard String of Every Contact Here i take one Cursor and
* this cursor is not null and its count>0 than i repeat one loop up to
* cursor.getcount() means Up to number of phone contacts. And in Every
* Loop i can make vcard string and store in Array list which i declared
* as a Global. And in Every Loop i move cursor next and print log in
* logcat.
* */
getVcardString();
}
private void getVcardString() {
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
Log.i("TAG two", "cursor" +cursor);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
Log.i("Number of contacts", "cursorCount" +cursor.getCount());
for (int i = 0; i < cursor.getCount(); i++) {
get(cursor);
Log.i("TAG send contacts", "Contact " + (i + 1) + "VcF String is" + vCard.get(i));
cursor.moveToNext();
}
StringBuffer s = new StringBuffer();
s.append( vCard.toString());
string = s.toString();
file = new File(string);
// Log.i("s", ""+s);
// Log.i("string", ""+string);
Log.i("file", ""+file);
} else {
Log.i("TAG", "No Contacts in Your Phone");
}
}
public void get(Cursor cursor) {
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Log.i("lookupKey", ""+lookupKey);
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
try {
AssetFileDescriptor 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);
String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, true);
mFileOutputStream.write(vcardstring.toString().getBytes());
vCard.add(storage_path);
} catch (Exception e1) {
e1.printStackTrace();
}
}
private void data() {
File filelocation = file;
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("vnd.android.cursor.dir/email");
sharingIntent.setType("application/x-vcard");
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+filelocation));
startActivity(Intent.createChooser(sharingIntent, "Send email"));
}
}
finally my issue is solved using like this
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = this;
button = (Button) findViewById(R.id.send);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
data();
}
});
/**
* This Function For Vcard And here i take one Array List in Which i
* store every Vcard String of Every Contact Here i take one Cursor and
* this cursor is not null and its count>0 than i repeat one loop up to
* cursor.getcount() means Up to number of phone contacts. And in Every
* Loop i can make vcard string and store in Array list which i declared
* as a Global. And in Every Loop i move cursor next and print log in
* logcat.
* */
getVcardString();
}
public static void getVcardString() {
String path = null;
String vfile = null;
vfile = "Contacts.vcf";
Cursor phones = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
null, null, null);
phones.moveToFirst();
Log.i("Number of contacts", "cursorCount" +phones.getCount());
for(int i =0;i<phones.getCount();i++) {
String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Log.i("lookupKey", " " +lookupKey);
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);
path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(path, true);
mFileOutputStream.write(VCard.toString().getBytes());
phones.moveToNext();
filevcf = new File(path);
Log.i("file", "file" +filevcf);
}catch(Exception e1) {
e1.printStackTrace();
}
}
Log.i("TAG", "No Contacts in Your Phone");
}
protected void data() {
File filelocation = filevcf ;
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("vnd.android.cursor.dir/email");
sharingIntent.setType("application/x-vcard");
sharingIntent.putExtra(Intent.EXTRA_EMAIL, "mail#gmail.com" );
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+filelocation.getAbsolutePath()));
startActivity(Intent.createChooser(sharingIntent, "Send email"));
}
I successfully tested the following. Changes to your code are indicated with comments beginning with "CHANGE:". Don't forget to have android.permission.WRITE_EXTERNAL_STORAGE in your manifest.
public class MainActivity extends Activity {
private String vfile;
private Cursor cursor;
private ArrayList<String> vCard;
private String string;
private File file;
private String storage_path; //CHANGE: storage_path global
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vCard = new ArrayList<String>();
Log.i("TAG one", "vfile" + vfile);
vfile = "Contacts" + "_" + System.currentTimeMillis() + ".vcf";
/**
* This Function For Vcard And here i take one Array List in Which i
* store every Vcard String of Every Contact Here i take one Cursor and
* this cursor is not null and its count>0 than i repeat one loop up to
* cursor.getcount() means Up to number of phone contacts. And in Every
* Loop i can make vcard string and store in Array list which i declared
* as a Global. And in Every Loop i move cursor next and print log in
* logcat.
* */
getVcardString();
data(); //CHANGE: now calling data to send vCard intent
}
private void getVcardString() {
cursor = getContentResolver().
query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
Log.i("TAG two", "cursor" +cursor);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
Log.i("Number of contacts", "cursorCount" +cursor.getCount());
for (int i = 0; i < cursor.getCount(); i++) {
get(cursor);
Log.i("TAG send contacts",
"Contact " + (i + 1) + "VcF String is" + vCard.get(i));
cursor.moveToNext();
}
// StringBuffer s = new StringBuffer(); CHANGE: not needed
// s.append( vCard.toString());
// string = s.toString();
// file = new File(string); //CHANGE: this is not what file should be
} else {
Log.i("TAG", "No Contacts in Your Phone");
}
}
public void get(Cursor cursor) {
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Log.i("lookupKey", ""+lookupKey);
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
try {
AssetFileDescriptor 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); //CHANGE: added this, so log statement in above method doesn't generate error
// String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
//CHANGE: this is the path we need to get file for intent:
storage_path = getExternalFilesDir(null).toString() + File.separator + vfile;
Log.i("MainActivity", storage_path);
//CHANGE: this will create the file we need:
file = new File(getExternalFilesDir(null), vfile);
file.createNewFile(); //CHANGE
//CHANGE: this will create the stream we need:
FileOutputStream mFileOutputStream = new FileOutputStream(file, true);
mFileOutputStream.write(vcardstring.toString().getBytes());
mFileOutputStream.close(); //don't forget to close
// vCard.add(storage_path); //CHANGE: not needed
} catch (Exception e1) {
e1.printStackTrace();
}
}
private void data() {
// File filelocation = file; //CHANGE: not what we need
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("vnd.android.cursor.dir/email");
sharingIntent.setType("application/x-vcard");
//CHANGE: using correct path:
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(storage_path));
startActivity(Intent.createChooser(sharingIntent, "Send email"));
}
}
how can i get the Contact ID and Contact group? i have used the following code which gives me the name and phone any all other info but not the id or the group
public void ExportContacts() {
vCard = new ArrayList<String>();
cursor = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
int ss = cursor.getCount();
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");
}
}
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 {
String _id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
fd = mContext.getContentResolver().openAssetFileDescriptor(uri, "_ID");
FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String vcardstring= new String(buf);
vCard.add(vcardstring);
String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, true);
mFileOutputStream.write(vcardstring.toString().getBytes());
} catch (Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
i want to put the ID and the Group name in the vCard that i write in file. can any one help?
Depending on which ID you want, you can use this or this for the ID field.
Group name is potentially somewhat messier: this is the row for group title, which may be what you need, but you probably need to do the appropriate error checking in case there isn't a group defined.
EDIT: Group ID you can find here.
I am programming a app that has to do a operation with high cpu usage on a longer time
the operation is startet like a service
but the android system kills the app because of the high cpu usage
so what can I do to reduce the cpu usage ?
and make the system not to stop my service ?
service :
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.IBinder;
import android.provider.ContactsContract;
public class backup_service extends Service {
int i;
int i2;
#Override
public void onCreate() {
try
{
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/dialog.db");
BufferedWriter out = new BufferedWriter(fstream);
out.write("on");
//Close the output stream
out.close();
backup();
}
catch (Exception x)
{
stopSelf();
}
}
#Override
public void onDestroy() {
util.deleteDir(new File("/data/data/contact.backup.alexander.fuchs/dialog.db"));
stopSelf();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void backup()
{
util.deleteDir(new File("/data/data/contact.backup.alexander.fuchs/backup/"));
new File("/data/data/contact.backup.alexander.fuchs/backup/").mkdirs();
// get it
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
i = 0;
i2 = 0;
while (cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// write
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/id.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(id);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/name.txt");
out = new BufferedWriter(fstream);
out.write(name);
//Close the output stream
out.close();
}
catch (Exception x)
{
}
if (Integer.parseInt(cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String number = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/number.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(number);
//Close the output stream
out.close();
}
catch(Exception x)
{
}
}
pCur.close();
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/email.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(email);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/email_type.txt");
out = new BufferedWriter(fstream);
out.write(emailType);
//Close the output stream
out.close();
}
catch(Exception x)
{
}
}
emailCur.close();
String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] noteWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams, null);
if (noteCur.moveToFirst()) {
String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
// write
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/note.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(note);
//Close the output stream
out.close();
}
catch (Exception x)
{
}
}
noteCur.close();
String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] addrWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, null, null, null);
while(addrCur.moveToNext()) {
String poBox = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
String street = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
String city = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
String state = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
String postalCode = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
String country = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
String type = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
// write
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/pobox.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(poBox);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/street.txt");
out = new BufferedWriter(fstream);
out.write(street);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/city.txt");
out = new BufferedWriter(fstream);
out.write(city);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/state.txt");
out = new BufferedWriter(fstream);
out.write(state);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/postalcode.txt");
out = new BufferedWriter(fstream);
out.write(postalCode);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/country.txt");
out = new BufferedWriter(fstream);
out.write(country);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"addres_type.txt");
out = new BufferedWriter(fstream);
out.write(type);
//Close the output stream
out.close();
}
catch (Exception x)
{
}
}
addrCur.close();
String imWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] imWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE};
Cursor imCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, imWhere, imWhereParams, null);
if (imCur.moveToFirst()) {
String imName = imCur.getString(
imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
String imType;
imType = imCur.getString(
imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE));
//write
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/im.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(imName);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/im_type.txt");
out = new BufferedWriter(fstream);
out.write(imType);
//Close the output stream
out.close();
}
catch(Exception x)
{
}
}
imCur.close();
String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (orgCur.moveToFirst()) {
String orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
String company = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
String department = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DEPARTMENT));
//write
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/orgName.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(orgName);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/title.txt");
out = new BufferedWriter(fstream);
out.write(title);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/company.txt");
out = new BufferedWriter(fstream);
out.write(company);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/department.txt");
out = new BufferedWriter(fstream);
out.write(department);
//Close the output stream
out.close();
}
catch(Exception x)
{
}
}
orgCur.close();
}
i++;
}
onDestroy();
}
}
}
You can try divide the operation into smaller pieces and place Thread.sleep() for a short time. If that's not enough try changing some code into loop like this:
Old code:
object.move(1000);
New code:
for (int i=0; i<100; i++) {
object.move(10);
Thread.sleep(10);
}
If the example move() operation takes more time if the given parameter is higher, the old code can cause your program non-responding. The new code will allow android to comunicate with your program during Thread.sleep(), so your app shoud not stop working.
#edit
As I can see in your code - you do have several while loops. Try placing Thread.sleep(10) inside them.
You're putting this code directly in a Service which runs on the main thread. You need to instead put it in a background thread. Consider using an IntentService instead or start a worker thread from your service.
I would like to get attachment from unread MMS messages, but the codes I have doesn't allow me to do so. How do I go about doing that?
Codes modified from here:
private void checkMMSMessages(){
// Create string arrays to store the queries later on
String[] columns = null;
String[] values = null;
// Calls the ContentResolver to query for columns with URI "content:mms"
Cursor curPdu = getContentResolver().query(Uri.parse("content://mms"), null, null, null, null);
if(curPdu.moveToNext()){
//String read = curRead.getString(curRead.getColumnIndex("read"));
// Gets ID of message
String id = curPdu.getString(curPdu.getColumnIndex("_id"));
// Gets thread ID of message
String thread_id = curPdu.getString(curPdu.getColumnIndex("thread_id"));
// Gets subject of message (if any)
String subject = curPdu.getString(curPdu.getColumnIndex("sub"));
// Gets date of message
String date = curPdu.getString(curPdu.getColumnIndex("date"));
String selectionAddr = new String ("msg_id = '" + id + "'");
Uri uriAddr = Uri.parse ("content://mms/" + id + "/addr");
Cursor curAddr = getContentResolver().query(uriAddr, null, null, null, null);
if(curAddr.moveToNext()){
String contact_id = curAddr.getString (curAddr.getColumnIndex ("contact_id"));
String address = curAddr.getString (curAddr.getColumnIndex ("address"));
String selectionPart = new String ("mid = '" + id + "'");
Cursor curPart = getContentResolver ().query(Uri.parse ("content://mms/part"), null, null, null, null);
//Cursor curPart = context.getContentResolver ().query(Uri.parse ("content://mms/" + id + "/part"), null, null, null, null);
while(curPart.moveToNext())
{
columns = curPart.getColumnNames();
if(values == null)
values = new String[columns.length];
for(int i=0; i< curPart.getColumnCount(); i++){
values[i] = curPart.getString(i);
}
String contact_idd = curPart.getString(0);
if(values[3].equals("image/jpeg") || values[3].equals("image/bmp") ||
values[3].equals("image/gif") || values[3].equals("image/jpg") ||
values[3].equals("image/png"))
{
GetMmsAttachment(values[0],values[12]);
//Toast.makeText(getApplicationContext(), "Retrieved MMS attachment", Toast.LENGTH_LONG);
}
}
}
}
}
private void GetMmsAttachment(String _id, String _data)
{
Uri partURI = Uri.parse("content://mms/part/" + _id );
String filePath = "/sdcard/photo.jpg";
InputStream is = null;
OutputStream picFile = null;
Bitmap bitmap = null;
try {
is = getContentResolver().openInputStream(partURI);
bitmap = BitmapFactory.decodeStream(is);
picFile = new FileOutputStream(filePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, picFile);
picFile.flush();
picFile.close();
}
catch (Exception e)
{
e.printStackTrace();
//throw new MmsException(e);
}
}
Figured out myself, the codes are as follows:
private void checkMMSMessages() {
String[] columns = null;
String[] values = null;
String read = "read = 0";
Cursor curPdu = getContentResolver().query(Uri.parse("content://mms"), null, read, null, null);
if(curPdu.moveToNext()){
String id = curPdu.getString(curPdu.getColumnIndex("_id"));
Cursor curPart = getContentResolver().query(Uri.parse ("content://mms/" + id + "/part"), null, null, null, null);
while(curPart.moveToNext())
{
columns = curPart.getColumnNames();
if(values == null)
values = new String[columns.length];
for(int i=0; i< curPart.getColumnCount(); i++){
values[i] = curPart.getString(i);
}
if(values[3].equals("image/jpeg") || values[3].equals("image/bmp") ||
values[3].equals("image/gif") || values[3].equals("image/jpg") ||
values[3].equals("image/png"))
{
GetMmsAttachment(values[0],values[12]);
}
}
}
}
private void GetMmsAttachment(String _id, String _data)
{
Uri partURI = Uri.parse("content://mms/part/" + _id );
String filePath = "/sdcard/photo.jpg";
InputStream is = null;
OutputStream picFile = null;
Bitmap bitmap = null;
try {
is = getContentResolver().openInputStream(partURI);
bitmap = BitmapFactory.decodeStream(is);
picFile = new FileOutputStream(filePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, picFile);
picFile.flush();
picFile.close();
}
catch (Exception e)
{
e.printStackTrace();
//throw new MmsException(e);
}
}
I think he asked how to retrieve the attachment from the server, as it is written UNREAD mms... If you have the column ct_l how to get the data from that internet address?