Not able to find android.provider.CONTACTS_STRUCTURE metadata of contact apps - android

I am trying to get the list of contact writable accounts in my device using the following code
public static final String SYNC_META_DATA = "android.content.SyncAdapter";
public static final String[] METADATA_CONTACTS_NAMES = new String[] {
"android.provider.ALTERNATE_CONTACTS_STRUCTURE",
"android.provider.CONTACTS_STRUCTURE"
};
final Intent intent = new Intent(SYNC_META_DATA).setPackage(resPackageName);
final List<ResolveInfo> intentServices =
pm.queryIntentServices(intent, PackageManager.GET_META_DATA);
if (intentServices != null) {
for (final ResolveInfo resolveInfo : intentServices) {
final ServiceInfo serviceInfo = resolveInfo.serviceInfo;
if (serviceInfo == null) {
continue;
}
for (String metadataName : METADATA_CONTACTS_NAMES) {
final XmlResourceParser parser = serviceInfo.loadXmlMetaData(
pm, metadataName);
if (parser != null) {
return parser;
}
}
}
}
but I am always getting XmlResourceParser parser as null. so please help me how can I fetch the list of contact writable accounts in android

There's an API for that, you need to iterate over all SyncAdapters and check if they supportUploading and have ContactsContract.AUTHORITY as their authority:
final SyncAdapterType[] syncs = ContentResolver.getSyncAdapterTypes();
for (SyncAdapterType sync : syncs) {
Log.d(TAG, "found SyncAdapter: " + sync.accountType);
if (ContactsContract.AUTHORITY.equals(sync.authority)) {
Log.d(TAG, "SyncAdapter supports contacts: " + sync.accountType + " - supportsUploading=" + sync.supportsUploading());
}
}
supportsUploading means that it's a two-way sync, i.e. the user can modify a contact on her device and have the changes synced up to their cloud account.

Related

PocketSphinx: How to recognize Keyword followed by dynamic word?

I have been working on PocketSphinx Android voice command project where the user can open application listed on their Android by use command "open xxx" (I made "open" as Keyword and xxx is application's name), but sadly it didn't work.
My question is, how PocketSphinx recognize two-words command, where the first word is Keyword and the second word is a dynamic word (user can say any application's name).
Declare keyword:
public class PocketSphinxActivity extends Activity implements
RecognitionListener {
/* Named searches allow to quickly reconfigure the decoder */
private static final String KWS_SEARCH = "wakeup";
/* Keyword we are looking for to activate menu */
private static final String KEYPHRASE = "open";
I tried to Split() two-words keyword (ex: open camera) and successfully opened camera, but what I need is "open xxx" so the user can define any application they want. That's why I change keyword to "open" only.
public void onPartialResult(Hypothesis hypothesis) {
if (hypothesis == null)
return;
String text = hypothesis.getHypstr();
String[] split = text.split("\\s+");
String word1 = split[0];
String word2 = split[1];
if (word2 != null) {
if (word1.equals("open")) {
PackageManager packageManager = getPackageManager();
List<PackageInfo> packs = packageManager.getInstalledPackages(0);
int size = packs.size();
boolean uninstallApp = false;
boolean exceptFlg = false;
for (int v = 0; v < size; v++) {
PackageInfo p = packs.get(v);
String tmpAppName = p.applicationInfo.loadLabel(packageManager).toString();
String pname = p.packageName;
tmpAppName = tmpAppName.toLowerCase();
if (tmpAppName.trim().toLowerCase().equals(word2.trim().toLowerCase())) {
PackageManager pm = this.getPackageManager();
Intent appStartIntent = pm.getLaunchIntentForPackage(pname);
if (null != appStartIntent) {
try {
this.startActivity(appStartIntent);
} catch (Exception e) {
}
}
}
}
finish();
public void onResult(Hypothesis hypothesis) {
((TextView) findViewById(R.id.result_text)).setText("");
if (hypothesis != null) {
String text = hypothesis.getHypstr();
String[] split = text.split("\\s+");
String word1 = split[0];
String word2 = split[1];
makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
}
Any help on this would be grateful. I really need it to complete my final project. Thank you.

How to Get the package Names of System pre-installed applications in Android

I Already know how to get the package names of applications installed by the user.
But i cannot figure out how to get the package names of applications that are preinstalled or are system-ware like (Samsung Fit, Calender etc.) ??
List<ApplicationInfo> packages = context.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo packageInfo : packages) {
Log.d(TAG, "Package :" + packageInfo.packageName);
Log.d(TAG, "Launcher Activity :" + pm.getLaunchIntentForPackage(packageInfo.packageName));
}
ApplicationInfo is having a packageName field which provides you package name of the application.
You can use below code to get the list of system application PackageInfo,
public static ArrayList<PackageInfo> getSystemPackageInfos(final Activity context) {
ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
ArrayList<String> packageNames = new ArrayList<String>();
PackageManager pm = context.getPackageManager();
List<PackageInfo> pinfoList = pm.getInstalledPackages(0);
Collections.sort(pinfoList, PackageNameComparator);
for (PackageInfo pinfo : pinfoList) {
packageNames.add(pinfo.packageName);
boolean isSystem = false;
if (((pinfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)) {
isSystem = false;
} else {
isSystem = true;
}
if (pinfo.applicationInfo.sourceDir.startsWith("/data/app/") && isSystem) {
//Non-system app
isSystem = false;
}
if (!isSystem) {
continue;
}
Bitmap icon = null;
Drawable apkIcon = getApplicationIcon(pinfo.applicationInfo, context);
try {
icon = Bitmap.createBitmap(apkIcon.getIntrinsicWidth(), apkIcon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(icon);
apkIcon.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
apkIcon.draw(canvas);
} catch (ClassCastException e) {
}
String name = pinfo.applicationInfo.loadLabel(pm).toString();
long apkSize = new File(pinfo.applicationInfo.sourceDir).length();
list.add(pinfo);
}
return list;
}

How to read files from Folder id in one drive (sky drive)?

I have successfuly signed in to Sky Drive account using Live Sdk (One Drive) libraries. And have also fetched the files and folder of the Root Directory of My One Drive (Sky Drive) account. Now i want to fetch files when i click on the the folder which is in the root directory.
I got my solution. Its simple and clean code i am here to paste for getting files from any folder id.
Just cancatinate 'files' after the folder id, like Folder_id+"/files" and it will retrieve all
the files
client.getAsync(Folder_id+"/files", new LiveOperationListener()
{
public void onComplete(LiveOperation operation)
{
final JSONObject result = operation.getResult();
final JSONArray data = result.optJSONArray("data");
if (result.has("error"))
{
final JSONObject error = result.optJSONObject("error");
final String message = error.optString("message");
final String code = error.optString("code");
ShowToast("mssg"+message);
return;
}
for (int i = 0; i < data.length(); i++)
{
final JSONObject oneDriveItem = data.optJSONObject(i);
if (oneDriveItem != null) {
final String itemName = oneDriveItem.optString("name");
final String itemType = oneDriveItem.optString("type");
final String ids=oneDriveItem.optString("id");
ShowToast("Folder ID = " + ids + ", name = " + itemName);
// ShowToast("Name: "+itemName+"\n"+"Type: "+itemType+"\n ID: "+ oneDriveItem.optString("id"));
}
}
//JSONObject result = operation.getResult();
Log.e("realllt",result.toString() );
}
public void onError(LiveOperationException exception, LiveOperation operation) {
resultTextView.setText("Error reading folder: " + exception.getMessage());
}
});

How can I get the list of all device admins (active as well as inactive ) in android?

The Google API allows us to get the list of all active admins in the device from the method: getActiveAdmins(). However, my requirement is that I want the list of all possible admins in the device , whether active or not. Is there some method to do so ?
Thanks
You can find list of applications by below code
final Intent deviceAdminIntent = new Intent("android.app.action.DEVICE_ADMIN_ENABLED", null);
final List<ResolveInfo> pkgAppsList = getPackageManager().queryBroadcastReceivers(deviceAdminIntent, 0);
for (ResolveInfo aResolveInfo : pkgAppsList) {
String pkg = aResolveInfo.activityInfo.applicationInfo.packageName;
String name = aResolveInfo.activityInfo.applicationInfo.loadLabel(getPackageManager()).toString();
System.out.println("Package :: " + pkg);
System.out.println("Name :: " + name);
}
You can get all the necessary data in the ResolveInfo of an application. You can check ResolveInfo javadoc here.
I wrote a method which returns the ComponentName as same as getActiveAdmins
private List<ComponentName> getAllAdmins(Context mContext) {
List<ComponentName> result = new ArrayList<ComponentName>();
// Read all receivers who can listen android.app.action.DEVICE_ADMIN_ENABLED
// You can add all other action which can be used for DeviceAdminReceiver
final Intent deviceAdminIntent = new Intent("android.app.action.DEVICE_ADMIN_ENABLED", null);
final List<ResolveInfo> pkgAppsList = mContext.getPackageManager().queryBroadcastReceivers(deviceAdminIntent, 0);
for (ResolveInfo aResolveInfo : pkgAppsList) {
// Prepare component and add to list
result.add(new ComponentName(aResolveInfo.activityInfo.applicationInfo.packageName,
aResolveInfo.activityInfo.name));
//String pkg = aResolveInfo.activityInfo.applicationInfo.packageName;
//String name = aResolveInfo.activityInfo.applicationInfo.loadLabel(getPackageManager()).toString();
//System.out.println("Package :: " + pkg);
//System.out.println("Name :: " + name);
}
return result;
}
You can find the necessary code in the following Android source for DeviceAdminSettings: https://android.googlesource.com/platform/packages/apps/Settings/+/kitkat-release/src/com/android/settings/DeviceAdminSettings.java
DevicePolicyManager mDPM; // = (DevicePolicyManager) getActivity().getSystemService(Context.DEVICE_POLICY_SERVICE);
final HashSet<ComponentName> mActiveAdmins = new HashSet<ComponentName>();
final ArrayList<DeviceAdminInfo> mAvailableAdmins = new ArrayList<DeviceAdminInfo>();
...
mActiveAdmins.clear();
List<ComponentName> cur = mDPM.getActiveAdmins();
if (cur != null) {
for (int i=0; i<cur.size(); i++) {
mActiveAdmins.add(cur.get(i));
}
}
mAvailableAdmins.clear();
List<ResolveInfo> avail = getActivity().getPackageManager().queryBroadcastReceivers(
new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
PackageManager.GET_META_DATA | PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS);
if (avail == null) {
avail = Collections.emptyList();
}
// Some admins listed in mActiveAdmins may not have been found by the above query.
// We thus add them separately.
Set<ComponentName> activeAdminsNotInAvail = new HashSet<ComponentName>(mActiveAdmins);
for (ResolveInfo ri : avail) {
ComponentName riComponentName =
new ComponentName(ri.activityInfo.packageName, ri.activityInfo.name);
activeAdminsNotInAvail.remove(riComponentName);
}
if (!activeAdminsNotInAvail.isEmpty()) {
avail = new ArrayList<ResolveInfo>(avail);
PackageManager packageManager = getActivity().getPackageManager();
for (ComponentName unlistedActiveAdmin : activeAdminsNotInAvail) {
List<ResolveInfo> resolved = packageManager.queryBroadcastReceivers(
new Intent().setComponent(unlistedActiveAdmin),
PackageManager.GET_META_DATA
| PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS);
if (resolved != null) {
avail.addAll(resolved);
}
}
}
for (int i = 0, count = avail.size(); i < count; i++) {
ResolveInfo ri = avail.get(i);
try {
DeviceAdminInfo dpi = new DeviceAdminInfo(getActivity(), ri);
if (dpi.isVisible() || mActiveAdmins.contains(dpi.getComponent())) {
mAvailableAdmins.add(dpi);
}
} catch (XmlPullParserException e) {
Log.w(TAG, "Skipping " + ri.activityInfo, e);
} catch (IOException e) {
Log.w(TAG, "Skipping " + ri.activityInfo, e);
}
}
getListView().setAdapter(new PolicyListAdapter());
This is how Android lists them for you in the Device Admins tab.

Need background running process

Actually I have written a method for updatiing server database using webservice from my application installed in the device using two IP Address.If one IP failed then it usess the second IP for upadting the data at server.
If Both the IP address failed i am saving the data to one of my sqllite database table tblTransaction.The code for that is given below.
private void Delay15Minute() throws IOException {
String server1IPAddress = "";
String server2IPAddress = "";
String deviceId = "";
Cursor cursorAdmin;
Cursor cursorTransaction;
adminhelper = new admin_helper(this);
cursorAdmin = adminhelper.GetAdminDetails();
if (cursorAdmin.moveToFirst())
server1IPAddress = cursorAdmin.getString(cursorAdmin
.getColumnIndex("RemoteServer1IPAddress"));
server2IPAddress = cursorAdmin.getString(cursorAdmin
.getColumnIndex("RemoteServer2IPAddress"));
deviceId = cursorAdmin.getString(cursorAdmin
.getColumnIndex("DeviceID"));
cursorAdmin.close();
ContentValues initialDelay15 = new ContentValues();
ContentValues initialTransaction = new ContentValues();
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
String RevisedEstimatedDate = sdf.format(date);
manifest_helper = new manifest_helper(this);
cursor = manifest_helper.GetDeliveries(pkManifest);
cursor.moveToFirst();
dbAdapter = new DatabaseAdapter(this);
dbAdapter.open();
for (int i = 0; i < cursor.getCount(); i++) {
cursor.getString(cursor.getColumnIndex("PKDelivery"));
String RevisedTime=cursor.getString(cursor.getColumnIndex("RevisedEstimatedDeliveryTime"));
// get hour and minute from time string
StringTokenizer st1 = new StringTokenizer(RevisedTime, ":");
int j = 0;
int[] val = new int[st1.countTokens()];
// iterate through tokens
while (st1.hasMoreTokens()) {
val[j] = Integer.parseInt(st1.nextToken());
j++;
}
// call time add method with current hour, minute and minutesToAdd,
// return added time as a string
String dateRevisedEstimatedDeliveryTime = addTime(val[0], val[1], 15);
initialDelay15.put("RevisedEstimatedDeliveryTime",
dateRevisedEstimatedDeliveryTime);
dbAdapter.UpdateRecord("tblDelivery", initialDelay15, "PKDelivery"
+ "=" + cursor.getString(cursor.getColumnIndex("PKDelivery")), null);
}
dbAdapter.close();
dataXmlExporter=new DataXmlExporter(this);
dataXmlExporter.StartDataSet();
cursor = manifest_helper.GetDeliveries(pkManifest);
dataXmlExporter.AddRowandColumns(cursor,"tblDelivery");
String sqlTransaction = "Select 6 as TransactionType,'Update Revised Estimated Delivery Time' as Description,"
+ " deviceId as DeviceID ,date() as TransactionUploadDate,time() as TransactionUploadTime from tblAdmin where PKAdmin > ?";
dbAdapter = new DatabaseAdapter(this);
dbAdapter.open();
cursorTransaction = dbAdapter.ExecuteRawQuery(sqlTransaction, "-1");
dataXmlExporter.AddRowandColumns(cursorTransaction, "Transaction");
String XMLTransactionData=dataXmlExporter.EndDataSet();
try {
if ((server1IPAddress != "") && (server2IPAddress != "")) {
try {
if (server1IPAddress != "") {
InsertUploadedTrancasctionDetails(server1IPAddress,
deviceId, XMLTransactionData);
}
} catch (Exception exception) {
if ((server1IPAddress != server2IPAddress)
&& (server2IPAddress != "")) {
InsertUploadedTrancasctionDetails(server2IPAddress,
deviceId, XMLTransactionData);
}
}
}
} catch (Exception exception) {
initialTransaction.put("ReceivedDate",
RevisedEstimatedDate);
initialTransaction.put("TransactionData",
XMLTransactionData);
dbAdapter.InsertRecord("tblTransaction", "",
initialTransaction);
}
dbAdapter.close();
LoadDeliveries(pkManifest);
}
The Problem is that i need to update the data to the server that stored in the tbltransaction automatically when we get connection to the serverIP along with my running application.I think it is possible by means of establishing backround running process along with my application that will check whethere data is there in the tbltransaction and connection with server is there.
So will any one have an idea for this ...if so please help meee...........
Here are a couple of methods that together will do just this. This is all within a Service, you could use a Handler instead and do this within an activity, but a Service is a wiser choice.
First, we need to be able to tell if we're online, this requires Network State and Wifi State Permissions:
public boolean isOnline() {
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo().isConnectedOrConnecting();
} catch (Exception e) {
return false;
}
}
Next we need to be able to set an alarm to retry. Add these variables:
private static AlarmManager am;
private static PendingIntent pIntent;
public static final int MSG_UPDATE = 0;
public static final String PENDING_REQ_KEY = "request";
And a set alarm method:
private synchronized void setAlarm() {
if (am == null) am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
if (Constants.LOG_DEBUG) Log.d(TAG,"Setting Alarm for 5 mins");
long delay = 300000L; //5 Mins
Intent i = new Intent(this,Service.class); //Reference the Service this method is in
i.putExtra(PENDING_REQ_KEY, MSG_UPDATE);
pIntent = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC,System.currentTimeMillis()+delay,pIntent);
}
Next, Override the onStartCommand method, to capture the update request:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getExtras() != null && intent.getExtras().containsKey(PENDING_REQ_KEY)) {
int request = intent.getExtras().getInt(PENDING_REQ_KEY);
if (request == MSG_UPDATE) update();
}
return START_STICKY;
}
finally, your update method:
public void update() {
if (isOnline()) {
/** Push data to server here */
}
else {
setAlarm();
}
}

Categories

Resources