Permission problem - Android Software Development

Hallo,
i want to add a new Contact in Android 6.0 but i get a permission problem and i dont now why.
This is my code:
Code:
Context cntx = getApplicationContext();
WritePhoneContact("John", "9999999999", cntx);
public void WritePhoneContact(String displayName, String number,Context cntx /*App or Activity Ctx*/)
{
Context contetx = cntx; //Application's context or Activity's context
String strDisplayName = displayName; // Name of the Person to add
String strNumber = number; //number of the person to add with the Contact
ArrayList<ContentProviderOperation> cntProOper = new ArrayList<ContentProviderOperation>();
int contactIndex = cntProOper.size();//ContactSize
//Newly Inserted contact
// A raw contact will be inserted ContactsContract.RawContacts table in contacts database.
cntProOper.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)//Step1
.withValue(RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null).build());
//Display name will be inserted in ContactsContract.Data table
cntProOper.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)//Step2
.withValueBackReference(Data.RAW_CONTACT_ID,contactIndex)
.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, strDisplayName) // Name of the contact
.build());
//Mobile number will be inserted in ContactsContract.Data table
cntProOper.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)//Step 3
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,contactIndex)
.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, strNumber) // Number to be added
.withValue(Phone.TYPE, Phone.TYPE_MOBILE).build()); //Type like HOME, MOBILE etc
try
{
// We will do batch operation to insert all above data
//Contains the output of the app of a ContentProviderOperation.
//It is sure to have exactly one of uri or count set
ContentProviderResult[] contentProresult = null;
contentProresult = contetx.getContentResolver().applyBatch(ContactsContract.AUTHORITY, cntProOper); //apply above data insertion into contacts list
}
catch (RemoteException exp)
{
//logs;
}
catch (OperationApplicationException exp)
{
//logs
}
}
Permission at the Manifest
Code:
<uses-spermission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
Error Messge: Permission Denial: writing com.android.providers.contacts.ContactsProvider2 uri content://com.android.contacts/raw_contacts from pid=32347, uid=10240 requires android.permission.WRITE_CONTACTS, or grantUriPermission()
Thank you for help

Uses-Spermission?

ageofempires said:
..... Error Messge: Permission Denial ....
Click to expand...
Click to collapse
I've had the same errors.
Don't know why.
Thoughts: Sync program on my PC is interfering when syncing Contacts and Agenda with Outlook.

<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
I Hope it helped!

Related

[Q] Get Location debbuging on device

Please,
I developed an application that use the current location.
Testing on local I can send the Latitude and Longitude by the DDM5 and I didn't have problem.
When I tried to do the same thing on debugging device, didn't work and on DDM5 I can't send this information.
Is there any setup to try this ?
Here is the code
<code>
//manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
//view.xml -> widget configure
private Location location;
private LocationManager lm;
private LocationListener locationListener;
//onCreate
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
//action
location.distanceTo........
private class MyLocationListener implements LocationListener
{
@Override
public void onLocationChanged(Location loc) {
if (loc != null) {
location = loc;
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
</code>
Thanks,
Luiz
I would like to know if anyone knows what is happening ?
if this is normal or no ?
when debug the android system on device, the Location API works normally or we need to simulate something ?
Thanks,
Luiz

Coding help(reboot)

Im trying to make a restart app for android for a senior class project but im having some trouble with the code. Anyone have tips or can help me out that would be great. I could message the code if they want.
look into something like this:
Code:
Intent reboot = new Intent(Intent.ACTION_REBOOT);
reboot.putExtra("nowait", 1);
reboot.putExtra("interval", 1);
reboot.putExtra("window", 0);
sendBroadcast(reboot);
Nvm you probably don't need the extras. You might so give it a try with and without
From something awesome
So would that go in the onCreate method?
Sent from my ADR6300 using XDA App
MrAwesomeMan said:
So would that go in the onCreate method?
Sent from my ADR6300 using XDA App
Click to expand...
Click to collapse
if you want your phone to reboot the second you start your app... then yes
i had that code in the onCreate method and i kept getting a force close error. So then i tried this:
Code:
[COLOR="Blue"]public class restart extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void boom(){
Intent reboot = new Intent(Intent.ACTION_REBOOT);
reboot.putExtra("nowait", 1);
reboot.putExtra("interval", 1);
reboot.putExtra("window", 0);
sendBroadcast(reboot);
}
public void myClickHandler(View view) {
boom();
}[/COLOR]
}
and when i click the button it doesnt do anything
here is the main.xml :
Code:
[COLOR="Blue"]<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:text="Restart" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
[/COLOR]
and here is the manifest
Code:
[COLOR="Blue"]<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="restart.android"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".restart"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<permission android:name="android.permission.DEVICE_POWER"/>
<uses-permission android:name="android.permission.DEVICE_POWER" />
<permission android:name="android.permission.REBOOT"/>
<uses-permission android:name="android.permission.REBOOT"/>
</manifest>[/COLOR]
Cause you never attached an onClickListener to your button. When i take a break in 15mins ill write an example
From something awesome
Code:
public class restart extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//get an instance of that button to be used in the code
Button rebootButton = (Button)findViewById(R.id.button1);
//attach an action to the button
rebootButton.setOnClickListener(new View.OnClickListener() {
//the action to partake upon pressage of said button
public void onClick(View view) {
boom();
}
});
}
public void boom() {
Intent reboot = new Intent(Intent.ACTION_REBOOT);
reboot.putExtra("nowait", 1);
reboot.putExtra("interval", 1);
reboot.putExtra("window", 0);
sendBroadcast(reboot);
}
}
whether boom() will work or not im not sure. but it will be called when you press the button.
-------------------
public static final String ACTION_REBOOT
Since: API Level 1
Broadcast Action: Have the device reboot. This is only for use by system code.
This is a protected intent that can only be sent by the system.
Constant Value: "android.intent.action.REBOOT"
killersnowman said:
public static final String ACTION_REBOOT
Since: API Level 1
Broadcast Action: Have the device reboot. This is only for use by system code.
This is a protected intent that can only be sent by the system.
Constant Value: "android.intent.action.REBOOT"
Click to expand...
Click to collapse
Well you can use, root + terminal commands.
http://stackoverflow.com/questions/4580254/android-2-2-reboot-device-programmatically
Code:
try {
Runtime.getRuntime().exec("su");
Runtime.getRuntime().exec("reboot");
} catch (IOException e) {
}
(Note: there is no error checking or anything special).
The first command will ask for superuser permission. The second, will reboot the phone. There is no need for extra permissions in the manifest file since the actual rebooting is handled by the executed comamand, not the app.
So i tried your code but boom() didnt work so i commented out the button instances in onCreate and put what was in boom() into onCreate but i still kept getting a window asking to force close. i also tried the try and catch loop in boom and in on create and they didnt work either.
Boom() wont work with out being signed as a system app, which would require you t compile your own rom. Try the superuser method above. You will need root
From something awesome
is there a way to shutdown the phone with a intent broadcast?
i was trying to use ACTION_SHUTDOWN instead of ACTION_REBOOT but it didnt works
thx for reply
##### EDIT
problem solved: need to put "ACTION_REQUEST_SHUTDOWN" to the Intent.
I'm a newbie here, so if you think anything is wrong with this post, feel free to point it out. I'm happy to learn.
I hope it's alright to piggyback on this thread, since half of it (the half of it that doesn't deal with using the linux-way of rebooting) actually deals with the same problem, even though it stems from an entirely different source.
In my case it's about sending a ACTION_PACKAGE_ADDED Intent... what's important is that it's protected the same way:
ActivityManagerService.java: broadcastIntentLocked
Code:
if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
|| callingUid == Process.SHELL_UID || callingUid == 0) {
// Always okay.
} else if (callerApp == null || !callerApp.persistent) {
So, it's about satisfying these requirements somehow, or getting around it by sending the broadcast directly.
As you say, you're supposed to sign applications with the same key as the applications in one of these groups to be able to use a sharedUserId, but that's cumbersome and would prevent the application from running on any device other but my own. It would also make updates a lot more complicated... so circumventing it seems the better idea. After all: I am root, so we're already way past any security considerations.
The first thing I've tried is modifying packages.xml , in the hope that the system wouldn't try to re-check the keys. Well, no such luck. From a security standpoint I don't think this check is necessary (if anybody is able to edit packages.xml it's already too late), but Android does it anyway, rebuilding the xml file. Maybe somebody has an idea where and how this re-building could be controlled? Or is it the other way around and the uid originates from somewhere else? It isn't the permission on the APK in /data/app, that's always system:system.
I've also tried starting the APK via "am" hoping that it might inherit the shell uid... it was a desperate attempt and it turned out exactly like anybody would have expected: it didn't work.
The next thing was changing the permission on the process while it's running. On some Linux flavors root can change the permissions in /proc/* , but apparently not on Android.
Then I tried to use ActivityManagerNative::broadcastIntent instead of Content::sendIntent, but the check is buried too deep (as I said before): in order to get past the check I would need access to ActivityManagerService::sendPackageBroadcastLocked , but the object I get through IActivityManager::getDefault is actually only a proxy (ActivityManagerProxy) that forwards the public commands via an IBinder. Naturally the proxy doesn't have the private methods (private methods can still be called, but the proxy is a pretty good isolation layer).
The only thing that I can still think of would be implementing sendPackageBroadcastLocked myself.. it really only depends on the threads, which might be accessible... somehow
Code:
for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--)
mLruProcesses.get(i).thread.dispatchPackageBroadcast(cmd, packages);
These are IApplicationThread objects... they are not implemented in Java... at least the file contains only the prototypes. Is there some way to interact with such objects directly from the shell?
I would be really grateful if anybody had any idea... I just refuse to believe that I'm the first person to need root access rights beyond the shell.

Interested in toggling a value in the build.prop

So in my toolkit, id like to design an activity where I could point it towards certain lines in the build.prop to allow a user to easily toggle, for instance this line
qemu.hw.mainkeys=0
So, in the layout xml, lets say it had "Enable Nav Bar" and a "Toggle Button" for on/off
Where would i start in developing such a feature?
You create a ToggleButton and whenever it is clicked, you change the line.
What is your problem?
nikwen said:
You create a ToggleButton and whenever it is clicked, you change the line.
What is your problem?
Click to expand...
Click to collapse
My concerns are wouldnt I need to add ro permissions on the prop before toggling and a reboot action to apply
I think your device needs to be rooted to be able to write to the build.prop file. You do not need root access to read it though
I'm from mobile and i can't post some code but i will give you some hints
To edit build.prop programmatically first you ne ed to be rooted then you can use the shell command "sed" to exchange values. Take a look at AOKP settings source on github and look for density changer class
If you want to import various build properties you can use fileinputstream and read the file line by line then let the app create listview custom items for every line in the file (you need a custom adapter) .
Sorry if this post it's not really useful but i will edit this when at PC
Sent from my HTC One X using Tapatalk 4 Beta
Thankyou for the tip! The answer might of been infront of my face possibly...
Sent from my 9300 using xda app-developers app
xcesco89 said:
I'm from mobile and i can't post some code but i will give you some hints
To edit build.prop programmatically first you ne ed to be rooted then you can use the shell command "sed" to exchange values. Take a look at AOKP settings source on github and look for density changer class
If you want to import various build properties you can use fileinputstream and read the file line by line then let the app create listview custom items for every line in the file (you need a custom adapter) .
Sorry if this post it's not really useful but i will edit this when at PC
Sent from my HTC One X using Tapatalk 4 Beta
Click to expand...
Click to collapse
I Wrote something up but I keep getting force closes "Not a java code monkey yet, still learning" and Ill post here what I have when I get to my pc later. Maybe you can see what Im missing or did wrong. What I did is I have a preference screen similiar to AOKP density changer class. What Im going for is a PreferenceList that you click and your values are Enable or Disabled and another preference to reboot to apply settings. Im wanting to allow the user to enable and disable the Navigation Bar by toggling it through the build.prop. If this works, I want to add more toggles custom values like change your phone model, Screen Density, build number, ect; but figured Id start with something simpler first and see if it works.
Sent from my Alps9300 using Tapatalk
Nx Biotic said:
I Wrote something up but I keep getting force closes "Not a java code monkey yet, still learning" and Ill post here what I have when I get to my pc later. Maybe you can see what Im missing or did wrong. What I did is I have a preference screen similiar to AOKP density changer class. What Im going for is a PreferenceList that you click and your values are Enable or Disabled and another preference to reboot to apply settings. Im wanting to allow the user to enable and disable the Navigation Bar by toggling it through the build.prop. If this works, I want to add more toggles custom values like change your phone model, Screen Density, build number, ect; but figured Id start with something simpler first and see if it works.
Sent from my Alps9300 using Tapatalk
Click to expand...
Click to collapse
this is the method you need:
Code:
private void setLcdDensity(int newDensity) {
Helpers.getMount("rw");
new CMDProcessor().su.runWaitFor("busybox sed -i 's|ro.sf.lcd_density=.*|"
+ "ro.sf.lcd_density" + "=" + newDensity + "|' " + "/system/build.prop");
Helpers.getMount("ro");
}
( method took from here : https://github.com/TeamBAKED/packag...aked/romcontrol/fragments/DensityChanger.java )
newDensity is the int/string you let the user set ( you can use a seekbar or a dialog or what you prefer)
you have also CMDProcessor().su.runWaitFor : just use the classes you can find here : https://github.com/TeamBAKED/packag...11bca71808c9143/src/com/baked/romcontrol/util
just add these classes in your project ( these are to simplify your life when you need to use android terminal [ remember to give credits on your app! ] )
Now, you can use various types of views and methods to show to the user all the available props:
- manually add every view for every line in your build.prop ( this will probably limit the compatibility with other devices and make your app "laggy" due to "gazilions" views )
- use a blank linearLayout and inflate a "row view" for every line in build.prop:
read file line by line and import every line in an ArrayList:
Code:
ArrayList<String> Tokens = new ArrayList<String>();
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("/system/build.prop");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
strLine = strLine.trim();
if ((strLine.length()!=0)) {
String[] names = strLine.split("\\s+");
Tokens.add(names[0]);
}
}
for (String s : Tokens) {
//System.out.println(s);
//Log.d("NNNNNNNNNNNNNNNNNN", s);
}
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
names = new String[Tokens.size()-1];
names = Tokens.toArray(names);
ArrayList<String> value = new ArrayList<String>();
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("/sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
strLine = strLine.trim();
if ((strLine.length()!=0)) {
String[] val = strLine.split("\\s+");
value.add(val[1]);
}
}
for (String s : value) {
//System.out.println(s);
//Log.d("NNNNNNNNNNNNNNNNNN", s);
}
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
values = new String[value.size()-1];
values = value.toArray(values);
LineNumberReader lnr = null;
try {
lnr = new LineNumberReader(new FileReader(new File("/sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table")));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
lnr.skip(Long.MAX_VALUE);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int num = lnr.getLineNumber();
Log.d("LINES", ""+num);
int i = 0;
//now inflate a specific view for every line
// you can also filter every item for example by reading the string and inflating a different layout using an if statement
for (String s : names) {
LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View v = inflater.inflate(R.layout.uvrow, null, true);
TextView text0 = (TextView) v.findViewById(R.id.text0);
ImageButton back0 = (ImageButton) v.findViewById(R.id.back0);
final EditText edit0 = (EditText) v.findViewById(R.id.edit0);
ImageButton fwd0 = (ImageButton) v.findViewById(R.id.fwd0);
text0.setText(s);
parentGroup.addView(v);
edit0.setText(values[i]);
/*
* if you need to set listeners and actions insert them inside this loop!
*/
}
if you need more informations, take a look at my code on github ( was my first "really useful" app ): https://github.com/cesco89/CustomSettings/blob/master/src/com/cesco/customsettings/UVTable.java
it's not perfect, could be tricky, but i can't post all the code here
This Is what I put together...Excuse any errors in java...Im new at this. When I start this fragment, I get a force close. What did I do?
Code:
package com.bionx.res.catalyst;
import android.content.Context;
import android.os.Bundle;
import android.os.PowerManager;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceFragment;
import com.bionx.res.R;
import com.bionx.res.helpers.CMDProcessor;
import com.bionx.res.helpers.Helpers;
public abstract class Navbar extends PreferenceFragment implements OnPreferenceChangeListener {
Preference mReboot;
ListPreference mStockValue;
int newStockValue;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.navbarchanger);
mStockValue = (ListPreference) findPreference("stock_value");
mStockValue.setOnPreferenceChangeListener(this);
mReboot = findPreference("reboot");
}
public boolean onPreference(Preference preference) {
if (preference == mReboot) {
PowerManager pm = (PowerManager) getActivity()
.getSystemService(Context.POWER_SERVICE);
pm.reboot("Setting Navbar");
}
return false;
}
[user=439709]@override[/user]
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference == mStockValue) {
newStockValue = Integer.parseInt((String) newValue);
setNavbarValue(newStockValue);
mStockValue.setSummary(getResources().getString(R.string.navbar_changer) + newStockValue);
return true;
}
return false;
}
private void setNavbarValue(int newNavbar) {
Helpers.getMount("rw");
new CMDProcessor().su.runWaitFor("busybox sed -i 's|qemu.hw.mainkeys=.*|"
+ "qemu.hw.mainkeys" + "=" + newNavbar + "|' " + "/system/build.prop");
Helpers.getMount("ro");
}
}
Code:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:title="System Properties"
android:summary="User System Tweaks" />
<ListPreference
android:entries="@array/navbar_stock_entries"
android:entryValues="@array/navbar_stock_values"
android:key="stock_value"
android:title="NavBar Enabler"
android:summary="Toggle the system navbar" />
<Preference
android:key="reboot"
android:title="Reboot"
android:summary="Applies tweaks and reboots" />
</PreferenceScreen>
Where I launch the fragment.
Code:
...
<header
android:fragment="com.bionx.res.catalyst.Navbar"
android:icon="@drawable/ic_changelog"
android:title="System Ui Tweaks"
android:summary="Developers soup of the week" />
...
Nx Biotic said:
This Is what I put together...Excuse any errors in java...Im new at this. When I start this fragment, I get a force close. What did I do?
Code:
package com.bionx.res.catalyst;
import android.content.Context;
import android.os.Bundle;
import android.os.PowerManager;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceFragment;
import com.bionx.res.R;
import com.bionx.res.helpers.CMDProcessor;
import com.bionx.res.helpers.Helpers;
public abstract class Navbar extends PreferenceFragment implements OnPreferenceChangeListener {
Preference mReboot;
ListPreference mStockValue;
int newStockValue;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.navbarchanger);
mStockValue = (ListPreference) findPreference("stock_value");
mStockValue.setOnPreferenceChangeListener(this);
mReboot = findPreference("reboot");
}
public boolean onPreference(Preference preference) {
if (preference == mReboot) {
PowerManager pm = (PowerManager) getActivity()
.getSystemService(Context.POWER_SERVICE);
pm.reboot("Setting Navbar");
}
return false;
}
[user=439709]@override[/user]
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference == mStockValue) {
newStockValue = Integer.parseInt((String) newValue);
setNavbarValue(newStockValue);
mStockValue.setSummary(getResources().getString(R.string.navbar_changer) + newStockValue);
return true;
}
return false;
}
private void setNavbarValue(int newNavbar) {
Helpers.getMount("rw");
new CMDProcessor().su.runWaitFor("busybox sed -i 's|qemu.hw.mainkeys=.*|"
+ "qemu.hw.mainkeys" + "=" + newNavbar + "|' " + "/system/build.prop");
Helpers.getMount("ro");
}
}
Code:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:title="System Properties"
android:summary="User System Tweaks" />
<ListPreference
android:entries="@array/navbar_stock_entries"
android:entryValues="@array/navbar_stock_values"
android:key="stock_value"
android:title="NavBar Enabler"
android:summary="Toggle the system navbar" />
<Preference
android:key="reboot"
android:title="Reboot"
android:summary="Applies tweaks and reboots" />
</PreferenceScreen>
Where I launch the fragment.
Code:
...
<header
android:fragment="com.bionx.res.catalyst.Navbar"
android:icon="@drawable/ic_changelog"
android:title="System Ui Tweaks"
android:summary="Developers soup of the week" />
...
Click to expand...
Click to collapse
please post the Log you get on Eclipse !
the log will tell you exactly where the error is

Webview offline caching: ERR_MISS_CACHE

Hello,
first of all, english is not my foreign language, but I hope you understand:
I made an app (only WebView) for opening a website. I want to make the app for offline-using. So I used getSettings().setAppCachePath() and getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY).
When I open a page connected to Wifi it works. But open the same page again it doesn't work and it's only shown: ERR_CACHE_MISS
What is wrong?
Here is my code:
Code:
public WebView mWebView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tischtennis);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.setWebViewClient(new MyAppWebViewClient());
// Enable Javascript
mWebView.getSettings().setJavaScriptEnabled(true);
// Cookies
CookieManager.getInstance().setAcceptCookie(true);
// CookieManager.getInstance().setAcceptThirdPartyCookies(true);
// Caching
mWebView.getSettings().setAppCacheMaxSize(1024*1024*10);
String cacheDir = getApplicationContext().getCacheDir().getAbsolutePath();
mWebView.getSettings().setAppCachePath(cacheDir);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.getSettings().setAllowFileAccess(true);
// Offline Support
if ( isNetworkAvailable() ) {
mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
} else {
mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY);
}
mWebView.loadUrl("www........");
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
And my Manifest-permissions:
Code:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Permission Denial when reading URI after RESTARTING the app

Hello everyone, I have an Android application that allows users to choose a photo for their profile as follows:
public void pickImage(View view) {
Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});
startActivityForResult(chooserIntent, 1);
}
@override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Context context = getApplicationContext();
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
if (data == null) {
//Display an error
return;
}
try {
ImageView im = findViewById(R.id.circularImageView);
uri = data.getData();
im.setImageURI(uri);
String image = uri.toString();
Log.d("ImageS", image);
SqlHelper db = new SqlHelper(this);
Intent i = getIntent();
String userid = i.getStringExtra("Name");
db.updateImage(userid, image);
}catch (Exception e){
}
//Now you can do whatever you want with your inpustream, save it as file, upload to a server, decode a bitmap...
}
}
Everything works fine and when I want to retrieve from my db the image everything works fine:
ImageView im1 = findViewById(R.id.circularImageView2);
im1.setImageURI(null);
String iS = db.getImage(name);
Log.d("ImageR", iS);
//
// Uri uri = Uri.parse(image);
//Log.d("Equals", String.valueOf(iS.equals(String.valueOf(R.drawable.imageuser))));
if(iS.equals(String.valueOf(R.drawable.imageuser))){ //Part to determine whether the user changed it or I use the default one
im1.setImageResource(Integer.parseInt(iS));
}else{
Uri uri = Uri.parse(iS);
ContentResolver contentResolver= getContentResolver();
ParcelFileDescriptor parcelFileDescriptor = null;
try {
parcelFileDescriptor = contentResolver.openFileDescriptor(uri, "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
try {
parcelFileDescriptor.close();
} catch (IOException e) {
e.printStackTrace();
}
im1.setImageBitmap(image);
}
The thing is that when I restart the application, I get the following error when going into an activity in which a user changed the image:
FATAL EXCEPTION: main
Process: com.example.arturopavon.finalproject, PID: 1445
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.arturopavon.finalproject/com.example.arturopavon.finalproject.MainActivity}: java.lang.SecurityException: Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord{47cb71a 1445:com.example.arturopavon.finalproject/u0a294} (pid=1445, uid=10294) requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6501)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.SecurityException: Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord{47cb71a 1445:com.example.arturopavon.finalproject/u0a294} (pid=1445, uid=10294) requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs
at android.os.Parcel.readException(Parcel.java:2004)
at android.os.Parcel.readException(Parcel.java:1950)
at android.app.IActivityManager$Stub$Proxy.getContentProvider(IActivityManager.java:4827)
at android.app.ActivityThread.acquireProvider(ActivityThread.java:5843)
at android.app.ContextImpl$ApplicationContentResolver.acquireUnstableProvider(ContextImpl.java:2526)
at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1783)
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1396)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1249)
at android.content.ContentResolver.openFileDescriptor(ContentResolver.java:1102)
at android.content.ContentResolver.openFileDescriptor(ContentResolver.java:1056)
at com.example.arturopavon.finalproject.MainActivity.onCreate(MainActivity.java:126)
at android.app.Activity.performCreate(Activity.java:7026)
at android.app.Activity.performCreate(Activity.java:7017)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1215)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
I have permissions set for my app to read internal storage but it is like it is not working after rebooting.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission
android:name="android.permission.MANAGE_DOCUMENTS"/>
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.MANAGE_DOCUMENTS};
for(String permission: permissions){
if (ContextCompat.checkSelfPermission(this, permission)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
permission)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(this,
permissions, 0);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
}
Any ideas on how to solve this?
I think the gallery app gives you temporary access to the photo (search FLAG_GRANT_READ_URI_PERMISSION).
As the solution, you can copy the photo into application folder and keep it there.
Your logcat says "requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs".
Have a look in the following link. It should give you an idea or possible solution...
https://stackoverflow.com/a/22178386

Categories

Resources