logo
down
shadow

Android KitKat (API 19) - How to write messages in SMS Content Provider, without sending them, from Non-Default App?


Android KitKat (API 19) - How to write messages in SMS Content Provider, without sending them, from Non-Default App?

By : Andrey Lima
Date : November 17 2020, 11:58 AM
Hope this helps The SmsWriteOpUtils class uses reflection to access methods of the AppOpsManager Service in order to enable/disable a non-default SMS app's write access to the SMS Provider in API Level 19 (KitKat). Once set, an app's access mode will be retained until it is reset, or the app is uninstalled.
Enabling an app's write access allows that app all of the standard methods of interaction with the SMS Provider, including insert() and delete().
code :
import android.app.AppOpsManager;
import android.content.Context;
import android.content.pm.PackageManager;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public final class SmsWriteOpUtils {
    private static final int WRITE_OP_CODE = 15;

    public static boolean isWriteEnabled(Context context) {
        int result = checkOp(context);
        return result == AppOpsManager.MODE_ALLOWED;
    }

    public static boolean setWriteEnabled(Context context, boolean enabled) {
        int mode = enabled ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED;
        return setMode(context, mode);
    }

    private static int checkOp(Context context) {
        try {
            Method checkOpMethod = AppOpsManager.class.getMethod("checkOp",
                                                                 Integer.TYPE,
                                                                 Integer.TYPE,
                                                                 String.class);

            AppOpsManager appOpsManager =
                (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            int uid = context.getApplicationInfo().uid;
            String packageName = context.getPackageName();

            return checkOpMethod.invoke(appOpsManager, WRITE_OP_CODE, uid, packageName);
        }
        catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return -1;
    }

    private static boolean setMode(Context context, int mode) {
        try {
            Method setModeMethod = AppOpsManager.class.getMethod("setMode",
                                                                 Integer.TYPE,
                                                                 Integer.TYPE,
                                                                 String.class,
                                                                 Integer.TYPE);

            AppOpsManager appOpsManager =
                (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            int uid = context.getApplicationInfo().uid;
            String packageName = context.getPackageName();

            setModeMethod.invoke(appOpsManager, WRITE_OP_CODE, uid, packageName, mode);

            return true;
        }
        catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }
}
boolean canWriteSms;

if(!SmsWriteOpUtils.isWriteEnabled(getApplicationContext())) {
    canWriteSms = SmsWriteOpUtils.setWriteEnabled(getApplicationContext(), true);
}
...


Share : facebook icon twitter icon
Start a content provider by default Android

Start a content provider by default Android


By : Jacka
Date : March 29 2020, 07:55 AM
hop of those help? Content providers are automatically created when your process starts up. This is not only the default behavior -- you cannot change it AFAIK.
So, if the user launches one of your activities (e.g., from the home screen), your content provider will be created before the activity is called with onCreate().
Receive MMS messages in Android KitKat

Receive MMS messages in Android KitKat


By : sridhar sikha
Date : March 29 2020, 07:55 AM
I hope this helps you . There's zero documentation so here's some info to help.
1) com.google.android.mms.pdu from source. You need the Pdu utils.
code :
TransactionSettings transactionSettings = new TransactionSettings(mContext, mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS).getExtraInfo());
private boolean beginMmsConnectivity() {
    try {
        int result = mConnMgr.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, Phone.FEATURE_ENABLE_MMS);
        NetworkInfo info = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
        boolean isAvailable = info != null && info.isConnected() && result == Phone.APN_ALREADY_ACTIVE && !Phone.REASON_VOICE_CALL_ENDED.equals(info.getReason());
        return isAvailable;
    } catch(Exception e) {
        return false;
    }
}
private static void ensureRouteToHost(ConnectivityManager cm, String url, TransactionSettings settings) throws IOException {
    int inetAddr;
    if (settings.isProxySet()) {
        String proxyAddr = settings.getProxyAddress();
        inetAddr = lookupHost(proxyAddr);
        if (inetAddr == -1) {
            throw new IOException("Cannot establish route for " + url + ": Unknown host");
        } else {
            if (!cm.requestRouteToHost(ConnectivityManager.TYPE_MOBILE_MMS, inetAddr))
                throw new IOException("Cannot establish route to proxy " + inetAddr);
        }
    } else {
        Uri uri = Uri.parse(url);
        inetAddr = lookupHost(uri.getHost());
        if (inetAddr == -1) {
            throw new IOException("Cannot establish route for " + url + ": Unknown host");
        } else {
            if (!cm.requestRouteToHost(ConnectivityManager.TYPE_MOBILE_MMS, inetAddr))
                throw new IOException("Cannot establish route to " + inetAddr + " for " + url);
        }
    }
}
private static int lookupHost(String hostname) {
    InetAddress inetAddress;
    try {
        inetAddress = InetAddress.getByName(hostname);
    } catch (UnknownHostException e) {
        return -1;
    }
    byte[] addrBytes;
    int addr;
    addrBytes = inetAddress.getAddress();
    addr = ((addrBytes[3] & 0xff) << 24) | ((addrBytes[2] & 0xff) << 16) | ((addrBytes[1] & 0xff) << 8) | (addrBytes[0] & 0xff);
    return addr;
}
private static void ensureRouteToHostFancy(ConnectivityManager cm, String url, TransactionSettings settings) throws IOException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    Method m = cm.getClass().getMethod("requestRouteToHostAddress", new Class[] { int.class, InetAddress.class });
    InetAddress inetAddr;
    if (settings.isProxySet()) {
        String proxyAddr = settings.getProxyAddress();
        try {
            inetAddr = InetAddress.getByName(proxyAddr);
        } catch (UnknownHostException e) {
            throw new IOException("Cannot establish route for " + url + ": Unknown proxy " + proxyAddr);
        }
        if (!(Boolean) m.invoke(cm, new Object[] { ConnectivityManager.TYPE_MOBILE_MMS, inetAddr }))
            throw new IOException("Cannot establish route to proxy " + inetAddr);
    } else {
        Uri uri = Uri.parse(url);
        try {
            inetAddr = InetAddress.getByName(uri.getHost());
        } catch (UnknownHostException e) {
            throw new IOException("Cannot establish route for " + url + ": Unknown host");
        }
        if (!(Boolean) m.invoke(cm, new Object[] { ConnectivityManager.TYPE_MOBILE_MMS, inetAddr }))
            throw new IOException("Cannot establish route to " + inetAddr + " for " + url);
    }
}
byte[] rawPdu = HttpUtils.httpConnection(mContext, mContentLocation, null, HttpUtils.HTTP_GET_METHOD, mTransactionSettings.isProxySet(), mTransactionSettings.getProxyAddress(), mTransactionSettings.getProxyPort());
private HashSet<String> getRecipients(GenericPdu pdu) {
    PduHeaders header = pdu.getPduHeaders();
    HashMap<Integer, EncodedStringValue[]> addressMap = new HashMap<Integer, EncodedStringValue[]>(ADDRESS_FIELDS.length);
    for (int addrType : ADDRESS_FIELDS) {
        EncodedStringValue[] array = null;
        if (addrType == PduHeaders.FROM) {
            EncodedStringValue v = header.getEncodedStringValue(addrType);
            if (v != null) {
                array = new EncodedStringValue[1];
                array[0] = v;
            }
        } else {
            array = header.getEncodedStringValues(addrType);
        }
        addressMap.put(addrType, array);
    }
    HashSet<String> recipients = new HashSet<String>();
    loadRecipients(PduHeaders.FROM, recipients, addressMap, false);
    loadRecipients(PduHeaders.TO, recipients, addressMap, true);
    return recipients;
}
private void loadRecipients(int addressType, HashSet<String> recipients, HashMap<Integer, EncodedStringValue[]> addressMap, boolean excludeMyNumber) {
    EncodedStringValue[] array = addressMap.get(addressType);
    if (array == null) {
        return;
    }
    // If the TO recipients is only a single address, then we can skip loadRecipients when
    // we're excluding our own number because we know that address is our own.
    if (excludeMyNumber && array.length == 1) {
        return;
    }
    String myNumber = excludeMyNumber ? mTelephonyManager.getLine1Number() : null;
    for (EncodedStringValue v : array) {
        if (v != null) {
            String number = v.getString();
            if ((myNumber == null || !PhoneNumberUtils.compare(number, myNumber)) && !recipients.contains(number)) {
                // Only add numbers which aren't my own number.
                recipients.add(number);
            }
        }
    }
}
private void processPduAttachments() throws Exception {
    if (mGenericPdu instanceof MultimediaMessagePdu) {
        PduBody body = ((MultimediaMessagePdu) mGenericPdu).getBody();
        if (body != null) {
            int partsNum = body.getPartsNum();
            for (int i = 0; i < partsNum; i++) {
                try {
                    PduPart part = body.getPart(i);
                    if (part == null || part.getData() == null || part.getContentType() == null || part.getName() == null)
                        continue;
                    String partType = new String(part.getContentType());
                    String partName = new String(part.getName());
                    Log.d("Part Name: " + partName);
                    Log.d("Part Type: " + partType);
                    if (ContentType.isTextType(partType)) {
                    } else if (ContentType.isImageType(partType)) {
                    } else if (ContentType.isVideoType(partType)) {
                    } else if (ContentType.isAudioType(partType)) {
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    // Bad part shouldn't ruin the party for the other parts
                }
            }
        }
    } else {
        Log.d("Not a MultimediaMessagePdu PDU");
    }
}
add new column in default contacts content provider of android

add new column in default contacts content provider of android


By : Max Lazzaroni
Date : March 29 2020, 07:55 AM
wish of those help No. This is not possible. Though it technically is, the end result will not be desirable:
Sent SMS message is automatically written to the content provider while it shouldn't in Cyanogenmod KitKat

Sent SMS message is automatically written to the content provider while it shouldn't in Cyanogenmod KitKat


By : Ivan Tsal-Tsalko
Date : March 29 2020, 07:55 AM
I hope this helps . I don't know why, but when I added sent and delivered pending intent new sms is not automatically added to content provider. This solved my problem
code :
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
                new Intent(SENT), 0);

PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
                new Intent(DELIVERED), 0);

sms.sendTextMessage(phoneNo, null, singlePart, sentPI, deliveredPI);
Do I need to write into SMS Provider when set as default SMS app on Android?

Do I need to write into SMS Provider when set as default SMS app on Android?


By : Igor
Date : March 29 2020, 07:55 AM
I hope this helps you . I read this blog and this doc about default SMS app behavior on Android KitKat+. Both say that: ,
If I were the default app on device, how do I insert the SMS?
Related Posts Related Posts :
  • Facebook login with Parse always returns false in user.isNew() Android
  • I get NullPointerException in an Android animation?
  • Things move out of place on different screen sizes
  • android database: the method open() is undefined for the type databasehelper class
  • sending intent with a parcelable extra from widget crashes on activity startup
  • How to record a video less than 10 mb using Android
  • Android - serialize object to pass it over Bluetooth NotSerializableException
  • Facebook Login Button Android in Eclipse
  • Null pointer exception on adding a marker to google maps
  • Jackson : Can not deserialize instance of java.util.ArrayList out of VALUE_TRUE token
  • How to customize PagerTitleStrip android
  • Click event not being captured for ListView items with HorizontalScrollView
  • HAX kernel module is not installed
  • Android: signed watchface on Android Wear 5.0 not installed
  • Dialog Builder in PreferenceFragment
  • HttpClient change UserAgent
  • Numerous 'No resource found' and 'Error retrieving parent' in Android Project
  • Get call log of a particular number
  • Invalid "--android-sdk" value "C:\android-sdk-win" in Titanium while deploying app on android mobile
  • Call onResume() method from Asynctask's onPostExecute() Method
  • Linking with native SO file present in included library project of Android
  • GridView error in horizontal spacing
  • Progressbar on bottom of listview item
  • Adding Markers on Google maps v2 Android
  • How to Remove Duplicate Libraries added via gradle?
  • Datepicker Dialog Validation...!
  • Scale image in ImageView to width of the parent and scale in height accordingly
  • user level api 19 failed to load. What files should i download
  • While running android AVD manager it shows error "HAX kernel module is not installed!"
  • Android application for limited enterprise audience
  • How to align different elements vertically in android studio?
  • Scroll View is not working when keyboard is open
  • Android phone Lg Realm(ls620) no driver found and can't find one online
  • Pros and cons for using external libraries in android project
  • What is the path of OAT file in Android 5.0
  • Actionbar Sherlock How to change drawer icon
  • how to pause progressbar in android
  • Styling composite views
  • Android, Eclipse: My app crashes on older API versions
  • Parcelable with arraylist<string> passing value from activity to fragment android
  • Why is there an extra part when parseUri() a String?
  • onItemClick and Toast don't work in a listfragment
  • Get input text with customview without edittext android
  • Getting value from the listview with custom adpter of selected checkbox to the activity
  • calculate value based on current and previous row in cursor android
  • How to save hashmap to shared preference?
  • How to Handle backPress with Fragment
  • DrawAllocation: Memory allocations within drawing code
  • Can I send Audio messages / notification in Android Auto?
  • Need layout design suggestion
  • Parse.com : Android how to store Image ParseFile in ParseObject in Offline Mode
  • Android Facebook LoginButton class not found
  • How to start another Activity using Button inside the Fragment
  • How to display video after getting from json?
  • Short black flashs when switching fragments in navigation drawer
  • Phonegap plugin does not work using remote build
  • Scrolling between dates in android
  • How to build system apps in Android Studio?
  • How to Display Dates in Calendar View from Database
  • How to give id of every fragment in and use it Tab Fragment android
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org