Related
All REMOVED by user request.
How-to
catch going to suspend: http://forum.xda-developers.com/showthread.php?p=2776841#post2776841
* more reserved *
Following up from post getting OT in thread:
ycavan said:
My opengl es init function is called after UpdateWindow(), so I'm still stumped as to why the surface still cannot be created... here's my winmain:
Click to expand...
Click to collapse
You might be missing some of the modern WM6 calls. Here's the relevant code from the working ported version of Graphics for the Masses.
I started with working code from the AppWizard. tabs/spaces is pushing the formatting everywhere:
Code:
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
MSG msg;
HACCEL hAccelTable;
int retval;
// Perform application initialization:
if (!InitInstance(hInstance, nCmdShow))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_APPSTUFF));
// Main message loop:
for(;;)
{
switch(gMinimized_mode)
{
case 0:
game_loop:
while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE) == TRUE)
{
if (GetMessage(&msg, NULL, 0, 0) )
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
else
{
retval = (int) msg.wParam;
goto out;
}
}
if (!gMinimized_mode)
{
/* app code */
eglSwapBuffers (eglDisplay, eglWindowSurface);
if(retval == 0)
{
/* app exit code */
goto out;
}
}
break;
default:
while (GetMessage(&msg, NULL, 0, 0) )
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
if (msg.message == WM_PAINT)
{
gMinimized_mode = 0;
goto game_loop;
}
}
retval = (int) msg.wParam;
goto out;
}
}
out:
return retval;
}
ATOM MyRegisterClass(HINSTANCE hInstance, LPTSTR szWindowClass)
{
WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPSTUFF));
wc.hCursor = 0;
wc.hbrBackground = NULL;//(HBRUSH) GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = 0;
wc.lpszClassName = szWindowClass;
return RegisterClass(&wc);
}
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
TCHAR szTitle[MAX_LOADSTRING]; // title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // main window class name
g_hInst = hInstance; // Store instance handle in our global variable
// SHInitExtraControls should be called once during your application's initialization to initialize any
// of the device specific controls such as CAPEDIT and SIPPREF.
SHInitExtraControls();
//LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
wcscpy(szTitle, appName);
LoadString(hInstance, IDC_OGLESEXFW, szWindowClass, MAX_LOADSTRING);
//If it is already running, then focus on the window, and exit
hWnd = FindWindow(szWindowClass, szTitle);
if (hWnd)
{
// set focus to foremost child window
// The "| 0x00000001" is used to bring any owned windows to the foreground and
// activate them.
SetForegroundWindow((HWND)((ULONG) hWnd | 0x00000001));
return 0;
}
if (!MyRegisterClass(hInstance, szWindowClass))
{
return FALSE;
}
hWnd = CreateWindow(szWindowClass, szTitle, WS_VISIBLE,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
// When the main window is created using CW_USEDEFAULT the height of the menubar (if one
// is created is not taken into account). So we resize the window after creating it
// if a menubar is present
if (g_hWndMenuBar)
{
RECT rc;
RECT rcMenuBar;
GetWindowRect(hWnd, &rc);
GetWindowRect(g_hWndMenuBar, &rcMenuBar);
rc.bottom -= (rcMenuBar.bottom - rcMenuBar.top);
MoveWindow(hWnd, rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top, FALSE);
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
{
/* EGL Setup */
EGLContext ctx;
EGLint majorVersion;
EGLint minorVersion;
//eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
eglDisplay = eglGetDisplay(GetDC(hWnd));
eglInitialize(eglDisplay, &majorVersion, &minorVersion);
eglConfig = select_config(eglDisplay, EGL_WINDOW_BIT, 16, 16, 4);
ctx = eglCreateContext(eglDisplay, eglConfig, NULL, NULL);
eglWindowSurface = eglCreateWindowSurface(eglDisplay, eglConfig, hWnd, NULL);
eglMakeCurrent(eglDisplay, eglWindowSurface, eglWindowSurface, ctx);
/* rest of app init */
}
return TRUE;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
static SHACTIVATEINFO s_sai;
switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_HELP_ABOUT:
DialogBox(g_hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, About);
break;
case IDM_OK:
SendMessage (hWnd, WM_CLOSE, 0, 0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_CREATE:
{
SHMENUBARINFO mbi;
memset(&mbi, 0, sizeof(SHMENUBARINFO));
mbi.cbSize = sizeof(SHMENUBARINFO);
mbi.hwndParent = hWnd;
mbi.nToolBarId = IDR_MENU;
mbi.hInstRes = g_hInst;
if (!SHCreateMenuBar(&mbi))
{
g_hWndMenuBar = NULL;
}
else
{
g_hWndMenuBar = mbi.hwndMB;
}
// Initialize the shell activate info structure
memset(&s_sai, 0, sizeof (s_sai));
s_sai.cbSize = sizeof (s_sai);
}
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code here...
EndPaint(hWnd, &ps);
if (!gMinimized_mode) eglSwapBuffer();
break;
case WM_DESTROY:
eglMakeCurrent(NULL, NULL, NULL, NULL);
eglDestroyContext(eglDisplay, eglContext);
eglDestroySurface(eglDisplay, eglWindowSurface);
eglTerminate(eglDisplay);
CommandBar_Destroy(g_hWndMenuBar);
PostQuitMessage(0);
break;
case WM_SIZE:
switch(wParam)
{
case SIZE_MINIMIZED:
gMinimized_mode = 1;
break;
case SIZE_MAXIMIZED: case SIZE_RESTORED: case SIZE_MAXSHOW:
gMinimized_mode = 0;
default:
{
RECT wrect;
GetClientRect(hwnd, &wrect);
/* app resize code */
break;
}
}
break;
case WM_ACTIVATE:
// Notify shell of our activate message
SHHandleWMActivate(hWnd, wParam, lParam, &s_sai, FALSE);
break;
case WM_SETTINGCHANGE:
SHHandleWMSettingChange(hWnd, wParam, lParam, &s_sai);
break;
case WM_KEYDOWN:
{
switch(wParam)
{
case(VK_UP):
break;
case(VK_DOWN):
break;
case(VK_LEFT):
break;
case(VK_RIGHT):
break;
case(VK_RETURN):
break;
}
if (wParam == VK_ESCAPE)
SendMessage(hwnd, WM_CLOSE, 0, 0);
break;
}
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
I'm using evc4, so I can't build for a THUMB ( wince 5.0 ) device... any way you can recompile the lib for ARMv4?
Otherwise, I'm still linking w/ the Vincent lib.
Anyway, I started a whole new app ( appwizard hello template ) instead of writing the winmain from scratch and I still cannot generate a surface when I have anything but EGL_NONE in the config requests.
One thing I note is that fps is about 47-48, but once again, the texture is not mapped onto the object. If I put it in my folder w/ the Vincent dll, the texture is mapped and the fps is about 11-12.
I'm not quite familiar w/ EGL, but... does anyone know the EGLConfig structure? I tried searching for it to see what the requested width/height per config was so I can debug why the surface just doesn't get created.
anyway, here's my code:
View attachment TestApp2.zip
ycavan said:
I'm using evc4, so I can't build for a THUMB ( wince 5.0 ) device... any way you can recompile the lib for ARMv4?
Click to expand...
Click to collapse
That's ARMv4 or ARMv4i? I'm going to assume latter because that's what most of the dlls seem to be targeting. I'll put this up soon.
Meantime, GetClientRect() on your hwnd and make sure the rect is sane before you pass it on to eglCreateWindowSurface().
Also, Imageon may work better with GLfloat values although it probably kills Vincent (with software emulation on the ARM without native FP support in armv6 by the compiler) with anything but GLfixed. Try some benchmarking to see which works out better.
100000xtimes thanks!
can you make a sourceforce project??
NuShrike said:
That's ARMv4 or ARMv4i? I'm going to assume latter because that's what most of the dlls seem to be targeting. I'll put this up soon.
Meantime, GetClientRect() on your hwnd and make sure the rect is sane before you pass it on to eglCreateWindowSurface().
.
Click to expand...
Click to collapse
ARMv4 is what evc4 targets...
GetClientRect() is giving me very sane values, 268x240... 268 due to the bars up top & below.
I guess I'm just confused as to why Vincent is able to properly create the proper surface while our drivers cannot...
Edit:
//eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
eglDisplay = eglGetDisplay(GetDC(hWnd));
eglInitialize(eglDisplay, &majorVersion, &minorVersion);
eglConfig = select_config(eglDisplay, EGL_WINDOW_BIT, 16, 16, 4);
ctx = eglCreateContext(eglDisplay, eglConfig, NULL, NULL);
eglWindowSurface = eglCreateWindowSurface(eglDisplay, eglConfig, hWnd, NULL);
eglMakeCurrent(eglDisplay, eglWindowSurface, eglWindowSurface, ctx);
/* rest of app init */
Click to expand...
Click to collapse
I just realized that you don't provide egl config attribs for for eglCreateWindowSurface or for eglCreateContext... huh. Doing that, the surface and context are created ok, but the texture still isn't loaded... mebbe a problem w/ texture loading.
NuShrike said:
That's ARMv4 or ARMv4i? I'm going to assume latter because that's what most of the dlls seem to be targeting. I'll put this up soon.
Meantime, GetClientRect() on your hwnd and make sure the rect is sane before you pass it on to eglCreateWindowSurface().
Also, Imageon may with better with GLfloat values although it probably kills Vincent (with software emulation on the ARM without native FP support in armv6 by the compiler) with anything but GLfixed. Try some benchmarking to see which works out better.
Click to expand...
Click to collapse
In the words of the great Sammy L.
ENGLISH MOTHAF*CKA DO YOU SPEAK IT!?!
Click to expand...
Click to collapse
cp_kirkley said:
In the words of the great Sammy L.
Click to expand...
Click to collapse
That's just rude, dood... lol
Anywho, it looks like the problem w/ texturing is that our drivers do not seem to support mipmap. By commenting out the linear mipmap flag when loading the texture, we get a fully working opengl es test app. I get about 44 fps.
See for yourselves.
View attachment testapp2.zip
@nushrike, both of your libgles_cm.lib's are designed for the 'THUMB' device. It's ok. I'll just keep on linking to the vincent lib.
Just remember that our driver does not support mipmap.
I think it's eVC is too old then. It's been thumb since WinCE5. Most all the system libs I have to link to insiste on Thumb -- if I set it to ARM, it refuses to link. Hey, that's an idea.. I'll try ARM to see if it generates any .lib.
For hardware, or supported mipmapping (software or not), look up glGenerateMipmapOES(GL_TEXTURE_2D). The tech demo I posted earlier demonstrates this. It's that blurry looking rotating texture behind the checker-board and various other textures.
edit: nope, can't create a dummy .lib by trying to link ARM.
Instead, you can modify Vincent to fake-support the extended functions as you need them and as they exist in the HWA .dll exports list. Here's an example:
Code:
#ifdef __GL_EXPORTS
# define GL_API __declspec(dllexport)
#else
# define GL_API
#endif
#define GL_APICALL GL_API
#define GL_APIENTRY
#ifdef __cplusplus
extern "C" {
#endif
{
GL_APICALL void GL_APIENTRY glGenerateMipmapOES (GLenum target)
{ return; }
#ifdef __cplusplus
}
#endif
NetrunnerAT said:
can you make a sourceforce project??
Click to expand...
Click to collapse
No code to make it a SourceForge project. Now, if it was code to make the drivers, that would be worthy.
ycavan: figured out your bug. You have to pass NULL for configAttrib (the last parameter) for eglCreateContext, and eglCreateWindowSurface. Also, using glGenerateMipmapOES(GL_TEXTURE_2D) with your source, texture works fine now. Same FPS. I'm seeing if converting to GLfloat will speed it up.
edit: float is no speed increase so far, but no decrease either.
ycavan said:
105171
Click to expand...
Click to collapse
How do you get this to run? I've already asked you in PM that WinCE doesn't support the concept of "current working directory" and you use in your code.
I'm sorry about not responding to the pm's... lol, I just didn't see them.
Anyway, just unzip the file on your pc and copy the exe and resources folder to your device and run the exe. Just make sure to keep the exe and resources folder together.
ycavan said:
Anyway, just unzip the file on your pc and copy the exe and resources folder to your device and run the exe. Just make sure to keep the exe and resources folder together.
Click to expand...
Click to collapse
It doesn't work for me after I drop it into the "Program Files" folder because this code is hard-coded for root directory then.
really odd... i ran the program in its own directory w/o a problem... i'm @ work, so i'll check it out when i get home.
it looks like the "resources" directory must be on the root of the device...
I'm working on finding the cwd, but loading resources fails even though it's the correct wd...
You guys can try and see if this works...
Code:
TCHAR tPath[255];
char sPath[255];
// get full path to this executable
GetModuleFileName(NULL,tPath,255);
// find the last '\'
TCHAR* pos = wcsrchr(tPath,'\\');
// end the string after the last '\'
*(pos+1) = '\0';
// copy wide char array to multi-byte string
wcstombs(sPath,tPath,255);
sPath should contain the working directory... but my app is failing the resource loads even though this is the same full path as before...
this can be very intresting for xda flame with goforce? can you build the libs because there is no SDK avialeble, the test app doesn't work message:
OpenGL ES init error:
eglInitialize
jaikben22 said:
this can be very intresting for xda flame with goforce? can you build the libs because there is no SDK avialeble, the test app doesn't work message:
OpenGL ES init error:
eglInitialize
Click to expand...
Click to collapse
EDIT:
Just realized that you're talking about another phone w/ the goforce... lol
You will need to prolly google "goforce opengl es sdk" There should be quite a few out there.
On another note... I figured out the problem with working directory resource loading.
I prefer to make a call once when it's something configuration-related... like storing my current working directory... it seems that evc4 doesn't like it when I do that so I had to update mesh.cpp and texture.cpp to perform the GetModuleFileName calls in each load function.
Here's an updated TestApp2. You just need to keep testapp2.exe and the resources directory together.
View attachment testapp2.zip
Updates include:
+ fullscreen now
+ up/down rotation
+ left/right acceleration -100 to 100
+ spouting of particles
Have fun guys.
The resources directory contains these files that you can change if you want to try different things.
spot.raw - the particle system's balls texture
font.raw - the font texture
knot.gsd - the main object mesh
fire128.tga - the mesh object's texture
lol for goforce there are none zero nada
Hi all,
I'm trying to have transparent PNGs on my screen.
What is the best way to doing this ? I'm in C#, I tried DirectX, but it doesn't work.
What am I doing wrong ?
My code :
Code:
using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.WindowsMobile.DirectX;
using Microsoft.WindowsMobile.DirectX.Direct3D;
using System.Runtime.InteropServices;
namespace Microsoft.Samples.MD3DM
{
// The main class for this sample
public class SimpleSMS : Form
{
// Our global variables for this project
Device device = null;
Texture texture = null;
Sprite sprite = null;
Rectangle rect;
public SimpleSMS()
{
// Set the caption
this.Text = "SimpleSMS";
this.MinimizeBox = false;
}
// Prepare the rendering device
public bool InitializeGraphics()
{
try
{
// Now let's setup our D3D parameters
PresentParameters presentParams = new PresentParameters();
presentParams.Windowed = true;
presentParams.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Default, this, CreateFlags.None, presentParams);
this.OnCreateDevice(device, null);
}
catch (DirectXException)
{
return false;
}
return true;
}
void OnCreateDevice(object sender, EventArgs e)
{
texture = TextureLoader.FromFile(device, @"badge.png");
sprite = new Sprite(device);
rect = new Rectangle(0, 0, 48, 48);
}
// All rendering for each frame occurs here
private void Render()
{
if (device != null)
{
device.Clear(ClearFlags.Target, System.Drawing.Color.Black, 1.0f, 0);
//Begin the scene
device.BeginScene();
device.RenderState.SourceBlend = Blend.SourceAlpha;
device.RenderState.DestinationBlend = Blend.InvSourceAlpha;
device.RenderState.AlphaBlendEnable = true;
sprite.Begin(SpriteFlags.AlphaBlend);
sprite.Draw(texture, rect, new Vector3(0.0f, 0.0f, 0.0f), new Vector3(100.0f, 100.0f, 0.0f), Color.White.ToArgb());
sprite.End();
//End the scene
device.EndScene();
device.Present();
}
}
// Called to repaint the window
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
// Render on painting
this.Render();
// Render again
this.Invalidate();
}
// Called to repaint the window background
protected override void OnPaintBackground(
System.Windows.Forms.PaintEventArgs e)
{
// Do nothing to ensure that the rendering area is not overdrawn
}
// Close the window when Esc is pressed
protected override void OnKeyPress(
System.Windows.Forms.KeyPressEventArgs e)
{
// Esc was pressed
if ((int)(byte)e.KeyChar == (int)System.Windows.Forms.Keys.Escape)
this.Close();
}
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
SimpleSMS frm = new SimpleSMS();
// Initialize Direct3D
if (!frm.InitializeGraphics())
{
MessageBox.Show("Could not initialize Direct3D. " +
"This tutorial will exit.");
return;
}
Application.Run(frm);
}
}
}
Thanks for answers,
Scuse my bad english :-/
Not sure this helps, but RLTODAY works very well with transparent pngs in any WM version, and recently he released the source code:
http://rotlaus-software.de/forum/index.php?topic=1847.0
You can use ImagingFactory in OpenNETCF or other wrapper over the internet. PNGs with alpha work work for me.
AlphaControls
There is a project on Codeplex that can help you with transparency called AlphaControls. Also have a look on codeproject at the iPhone app clone
moneytoo said:
You can use ImagingFactory in OpenNETCF or other wrapper over the internet. PNGs with alpha work work for me.
Click to expand...
Click to collapse
Thank you all for answers ...
I tried OpenNetCF, without any result.
Do you have a piece of code in example ?
Try this:
http://www.codeplex.com/alphamobilecontrols
Or this:
http://johan.andersson.net/blog/2007/10/solution-for-transparent-images-on.html
Hey peeps,
Heres a fun challenge for you expert androiders out there.
I am a n00b with android and so far I have created a listview that gets the "name" of mp3 tracks from my sql server database in which I have a name field.
Here is how I acheive that:
Code:
private void connect() {
String data;
List<String> r = new ArrayList<String>();
ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r);
ListView list=(ListView)findViewById(R.id.listView1);
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("myServerAddress.getfiles"); //ADD SERVER ADDRESS WHERE FILE IS HOSTED
HttpResponse response = client.execute(request);
HttpEntity entity=response.getEntity();
data=EntityUtils.toString(entity);
Log.e("STRING", data);
try {
JSONObject jsonResponse = new JSONObject(data);
JSONArray jsonMainNode = jsonResponse.optJSONArray("mp3s");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
//String ID = jsonChildNode.getString("ID");
String name = jsonChildNode.getString("Name");
Log.e("STRING", name);
//r.add(ID);
r.add(name);
list.setAdapter(adapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClientProtocolException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
} catch (IOException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
}
What I desperately need is:
A method that, when the user clicks on the listview item "name" it relates it to the "name" field in my database BUT fetches the "url" field in my database, realises its a weblink and streams the weblink as a service, opens up media player or whatever on users phone and begins streaming the audio file...
Right so I know I need:
- a onItemClick listener method
- I believe I need to open the connection to database again (not sure)
- I need to do some matching i.e. if listview item "name" == database.name then get URL field from database
- open player on users device
- stream music file.
Please can you help me acheive this?
Thanks in advance...
I actually got it to play the file with this code:
Code:
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
if (list.getItemAtPosition(position)==name) {
MediaPlayer mp = MediaPlayer.create(getApplicationContext(),FileName);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
}
});
But the problem is:
- it only plays the last file in a listview of 3 items
- if the mp3 is already playing it will start to play again , so it plays 2 files
- the other 2 tracks in the list do not play
please help
thanks
I love Android. I want to learn to develop apps. I keep reading tutorials. I got dissapointed and read about HTML frameworks (phonegap, etc). I came back to Android Native Java. I want to learn from the roots. However, some things discourages me....
All this part of the code is just for making a request to the Openweather API and get the json data (plus a little debugging stuff); which in Python or similar languages you only have to care about
- importing the library that handles http requests
- make the request in one function and save it into a json object
Code:
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int numDays = 7;
try {
final String FORECAST_BASE_URL =
"<the-domain>/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built URI " + builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "Forecast string: " + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
This is the complete Class:
Code:
public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
/* The date/time conversion code is going to be moved outside the asynctask later,
* so for convenience we're breaking it out into its own method now.
*/
private String getReadableDateString(long time){
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to valid date.
Date date = new Date(time * 1000);
SimpleDateFormat format = new SimpleDateFormat("E, MMM d");
return format.format(date).toString();
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(double high, double low) {
// For presentation, assume the user doesn't care about tenths of a degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
*
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DATETIME = "dt";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
String[] resultStrs = new String[numDays];
for(int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read "1400356800" as
// "this saturday".
long dateTime = dayForecast.getLong(OWM_DATETIME);
day = getReadableDateString(dateTime);
// description is in a child array called "weather", which is 1 element long.
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
// Temperatures are in a child object called "temp". Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " + highAndLow;
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
return resultStrs;
}
@Override
protected String[] doInBackground(String... params) {
// If there's no zip code, there's nothing to look up. Verify size of params.
if (params.length == 0) {
return null;
}
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int numDays = 7;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page
final String FORECAST_BASE_URL =
"<the-domain>/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built URI " + builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "Forecast string: " + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getWeatherDataFromJson(forecastJsonStr, numDays);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
// This will only happen if there was an error getting or parsing the forecast.
return null;
}
}
I mean, I know this code can be reduced, but I'm angry about the way it works. Everything needs to be passed to another object! And even rembember all those castings! Castings everywhere!
- The builded URI to the URL.
- The URL to the HttpConection variable.
- Once you connect, save that into the InputStream.
- Make a StringBuffer because we are going to send line by line everything.
- Then create the reader = new BufferedReader(new InputStreamReader(inputStream)).
- Append the lines to the buffer and return if it's ok.
- Else catch all the errors and be sure to close all the connections.
Damn Java !
Forgive me. You'll hate me.
Java is readable, that's the truth... but don't tell me that it is easy for a normal person.
Am I the only one?
If you are a beginner and will straight move to these classes. You will obviously find Java difficult. But Java is very easy if you move step by step from start
Sent from my XT1033 using XDA Premium 4 mobile app
---------- Post added at 04:18 PM ---------- Previous post was at 04:16 PM ----------
And that library also does the same thing inside. Only difference is, your work is already done by author of the library.
Sent from my XT1033 using XDA Premium 4 mobile app
Java is definitely a very verbose language but it's also widely used and so you will find many libraries that do tasks like grab JSON data from a service that have already been implemented for you
manwoman said:
Damn Java !
Forgive me. You'll hate me.
Java is readable, that's the truth... but don't tell me that it is easy for a normal person.
Am I the only one?
Click to expand...
Click to collapse
I don't think you're the only one. It's easy to get scared away by the many too verbose examples available, the key is to look at what you're trying to achieve and then break it up into those parts.
Your code listing is (I think) an attempt to show all steps to get the forecast data, but if that would have been broken up into smaller steps I don't think you'd look at it as quite as bad.
You would then have methods like
Code:
URL getForecastUrl(String parameter);
Code:
BufferedReader getUrl(URL url) { }
Code:
String readAll(BufferedReader reader) {}
Each of which would have had something like 6-7 lines of simple, cohesive code.
I understand your point, but in this particular scenario I think you're the victim of a poorly structured code sample rather than a too verbose language.
If you think the default implementation is too complicated, here are also many java libraries which will make your life easier.
Hi guys, could anyone help me with this?
I am trying to develop an application that could automatic change the ringtone for incoming calls, because all the existed applications which has this feature could not works well on my Galaxy S7 Edge,
but then I found out is't not that easy to change ringtone on Galaxy S7 Edge.
I am tried with these code:
File sdFile = new File("/mnt/storage/26D9-150C/test.mp3");
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, sdFile.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, sdFile.getName());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(sdFile.getAbsolutePath());
getContentResolver().delete(uri ,null ,null);//if not delete, maybe it will cause some error.
Uri newUri = this.getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE, newUri);
These code works fine on other devices, also on the Galaxy S7 Edge, you can see the new ringtone with code below, the ringtone changed into the target file, but when you received a phone call it's not the the ringtone that I set ! It's still the old ringtone before I run that code above. What's the problem ????? And I checked the ringtone from "Setting-Sound and vibrate-ringtone-incoming ringtone" it's never changed!!!
And I have granted the WRITE_SETTINGS permission already.
private Uri getSystemDefaultRingtoneUri() {
return RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE);//RingtoneManager.TYPE_ALL
}
private String getRealPath(Uri fileUrl) {
String fileName = null;
Uri filePathUri = fileUrl;
if (fileUrl != null) {
if (fileUrl.getScheme().toString().compareTo("content") == 0) {
Cursor cursor = mContext.getContentResolver().query(fileUrl, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
fileName = cursor.getString(column_index);
if (!fileName.startsWith("/mnt")) {
fileName = "/mnt" + fileName;
}
cursor.close();
}
} else if (fileUrl.getScheme().compareTo("file") == 0) {
fileName = filePathUri.toString().replace("file://", "");
if (!fileName.startsWith("/mnt")) {
fileName += "/mnt";
}
}
}
return fileName;
}
Then I searched everywhere, and find out that it seems samsung changed the system, the TYPE_RINGTONE will not effect on samsung anymore, is it true ? How could fix this problem ?
Why samsung change it like this ? It's really ****ty for developers!
Could anyone help me ? Thank you!
And here is all the code:
public class ActivityMain extends AppCompatActivity {
private static final boolean d = true;
private Context mContext;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
initView();
checkMyPermission(false);
}
private boolean checkMyPermission(boolean isSecondTimeCheck) {
String dialogTitle = "need WRITE_SETTINGS permission";
if (isSecondTimeCheck) dialogTitle = "you deny the permission";
String btnTitle = "ok", if (isSecondTimeCheck) btnTitle = "try again";
if (Build.VERSION.SDK_INT >= 23) {
if (!Settings.System.canWrite(this)) {
new AlertDialog.Builder(mContext).setMessage(dialogTitle).setPositiveButton(btnTitle, new DialogInterface.OnClickListener() {
@override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, REQUEST_CODE_PERMISSION);
}
}).setNegativeButton("cancel", null).create().show();
return false;
}
return true;
} else {
int hasWriteContactsPermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_SETTINGS);
if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
new AlertDialog.Builder(mContext).setMessage(dialogTitle).setPositiveButton(btnTitle, new DialogInterface.OnClickListener() {
@override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, REQUEST_CODE_PERMISSION);
}
}).setNegativeButton("cancel", null).create().show();
return false;
} else {
return true;
}
}
}
private void initView() {
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View view) {
//TODO I added the event here, it's more easier......this is the automatic method
// Log.d("tag", "original ringtone before set new ringtone" + getRealPath(getSystemDefaultRingtoneUri()));
// setMyRingtone("/mnt/storage/26D9-150C/0_MyFiles/8.Others/New_Eng_Rings_15.09.03/Blame it on me - akon - A.mp3");
// //setMyRingtone("/mnt/storage/26D9-150C/0_MyFiles/8.Others/New_Eng_Rings_15.09.03/Birthmark - akon - A.mp3");
//TODO here is the 2nd method, manual setting also not work....
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Choose the new ringtone");
startActivityForResult(intent, REQUEST_CODE_CHOOSE_RINGTONE_BY_USER);
}
});
}
private static final int REQUEST_CODE_PERMISSION = 1;
private static final int REQUEST_CODE_CHOOSE_RINGTONE_BY_USER = 2;
private void setMyRingtone(String path) {
File sdFile = new File(path);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, sdFile.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, sdFile.getName());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(sdFile.getAbsolutePath());
getContentResolver().delete(uri, null, null);
Uri newUri = this.getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE, newUri);
Log.d("tag", "new ringtone has been set:" + getRealPath(getSystemDefaultRingtoneUri()));//you can see that the new ringtone has been set success!
}
private Uri getSystemDefaultRingtoneUri() {
return RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE);//RingtoneManager.TYPE_ALL
}
private String getRealPath(Uri fileUrl) {
String fileName = null;
Uri filePathUri = fileUrl;
if (fileUrl != null) {
if (fileUrl.getScheme().toString().compareTo("content") == 0) {
Cursor cursor = mContext.getContentResolver().query(fileUrl, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
fileName = cursor.getString(column_index);
if (!fileName.startsWith("/mnt")) {
fileName = "/mnt" + fileName;
}
cursor.close();
}
} else if (fileUrl.getScheme().compareTo("file") == 0) {
fileName = filePathUri.toString().replace("file://", "");
if (!fileName.startsWith("/mnt")) {
fileName += "/mnt";
}
}
}
return fileName;
}
/* 当设置铃声之后的回调函数 */
@override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE_PERMISSION:
checkMyPermission(true);
break;
case REQUEST_CODE_CHOOSE_RINGTONE_BY_USER:
if (resultCode == RESULT_OK) {
try {
Uri pickedUri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if (pickedUri != null) {
Log.d("tag", "new ringtone will be set into:" + getRealPath(pickedUri));
RingtoneManager.setActualDefaultRingtoneUri(mContext, RingtoneManager.TYPE_RINGTONE, pickedUri);
Log.d("tag", "new ringtone has been set into:" + getRealPath(getSystemDefaultRingtoneUri()));
}
} catch (Exception e) {
if (d) e.printStackTrace();
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Please help, thank you.
is anyone could help ?
help....
You need the
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
Permission. Only grantable for System apps.
nicholaschum said:
You need the
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
Permission. Only grantable for System apps.
Click to expand...
Click to collapse
Thanks for your reply.
I have this permission in my manifest.xml already.
It seems samsung ringtong not use the standard database...
Cooper.G said:
Thanks for your reply.
I have this permission in my manifest.xml already.
It seems samsung ringtong not use the standard database...
Click to expand...
Click to collapse
As I said, your app must be a system app (or a privileged app). Or else, adding this manifest to a normal app will not function at all and is useless.
nicholaschum said:
As I said, your app must be a system app (or a privileged app). Or else, adding this manifest to a normal app will not function at all and is useless.
Click to expand...
Click to collapse
Actually I think it's not the metter about the permission, the permission has been authorized, and the ringtone really changed into my ringtone on my device,
use these code you can see the default ringtone has changed after set.
private Uri getSystemDefaultRingtoneUri() {
return RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE);//RingtoneManager.TYPE_ALL
}
Also use a different application to check the default ringtone, it's changed into the one that I choosen.
But in fact the the ring of incoming call from the speaker never changed.
So I think samsung use a different ringtone database or whatever.
Oh, and all kinds of random ringtong tools not work on S7edge.
I will try to figure it out when I rooted my s7edge.
And before this, I found some information about samsung ring of alarm, so I think the call maybe the same reason, http://bbs.anzhuo.cn/thread-938419-1-1.html
anyway, thanks for reply.
nicholaschum said:
As I said, your app must be a system app (or a privileged app). Or else, adding this manifest to a normal app will not function at all and is useless.
Click to expand...
Click to collapse
And here is the way for android 6.0.1 to ask the WRITE_SETTINGS permission
private boolean checkMyPermission(boolean isSecondTimeCheck) {
String dialogTitle = "need WRITE_SETTINGS permission";
if (isSecondTimeCheck) dialogTitle = "you deny the permission";
String btnTitle = "ok", if (isSecondTimeCheck) btnTitle = "try again";
if (Build.VERSION.SDK_INT >= 23) {
if (!Settings.System.canWrite(this)) {
new AlertDialog.Builder(mContext).setMessage(dialogTit le).setPositiveButton(btnTitle, new DialogInterface.OnClickListener() {
@override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, REQUEST_CODE_PERMISSION);
}
}).setNegativeButton("cancel", null).create().show();
return false;
}
return true;
} else {
int hasWriteContactsPermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_SETTINGS);
if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
new AlertDialog.Builder(mContext).setMessage(dialogTit le).setPositiveButton(btnTitle, new DialogInterface.OnClickListener() {
@override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, REQUEST_CODE_PERMISSION);
}
}).setNegativeButton("cancel", null).create().show();
return false;
} else {
return true;
}
}
}
Cooper.G said:
Actually I think it's not the metter about the permission, the permission has been authorized, and the ringtone really changed into my ringtone on my device,
use these code you can see the default ringtone has changed after set.
private Uri getSystemDefaultRingtoneUri() {
return RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE);//RingtoneManager.TYPE_ALL
}
Also use a different application to check the default ringtone, it's changed into the one that I choosen.
But in fact the the ring of incoming call from the speaker never changed.
So I think samsung use a different ringtone database or whatever.
Oh, and all kinds of random ringtong tools not work on S7edge.
I will try to figure it out when I rooted my s7edge.
And before this, I found some information about samsung ring of alarm, so I think the call maybe the same reason, http://bbs.anzhuo.cn/thread-938419-1-1.html
anyway, thanks for reply.
Click to expand...
Click to collapse
The permission has NOT been authorized. Please try to wrap your head around this. Your code is really messy.
https://github.com/android/platform_frameworks_base/blob/master/core/res/AndroidManifest.xml#L1597
Line 1600 states that you must have built the system through same firmware signature, "preinstalled" (priv-app), appop and pre-23 API
1595 states that it has a protection level of signature meaning that if the app isn't signed with the same signature as the ROM it won't be authorized to use that permission.
You can also try "pm grant YOUR_APP_NAME android.permission.WRITE_SETTINGS" in adb shell - and you will get an error saying it isn't a grantable permission.
Finally, if your app is a downloadable app from Play Store, this is the only caveat. Unless you request root to priv-app, THIS PERMISSION ISN'T GRANTED.
Java:
private boolean checkWriteSettingsPermissions() {
String permission = "android.permission.WRITE_SETTINGS";
int res = getContext().checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
This is simple code that allows you to check whether your app is granted the permission.
nicholaschum said:
The permission has NOT been authorized. Please try to wrap your head around this. Your code is really messy.
https://github.com/android/platform_frameworks_base/blob/master/core/res/AndroidManifest.xml#L1597
Line 1600 states that you must have built the system through same firmware signature, "preinstalled" (priv-app), appop and pre-23 API
1595 states that it has a protection level of signature meaning that if the app isn't signed with the same signature as the ROM it won't be authorized to use that permission.
You can also try "pm grant YOUR_APP_NAME android.permission.WRITE_SETTINGS" in adb shell - and you will get an error saying it isn't a grantable permission.
Finally, if your app is a downloadable app from Play Store, this is the only caveat. Unless you request root to priv-app, THIS PERMISSION ISN'T GRANTED.
Java:
private boolean checkWriteSettingsPermissions() {
String permission = "android.permission.WRITE_SETTINGS";
int res = getContext().checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
This is simple code that allows you to check whether your app is granted the permission.
Click to expand...
Click to collapse
Thank you for your patient.
1. I tried your code, and I was wrong about the permission, it says PERMISSION_DENIED. but I think this is not the problem for this question.
2. Did you tried my code ? The way that I asked for "WRITE_SETTINGS" is really work for ringtone, altho
Java:
private boolean checkWriteSettingsPermissions() {
String permission = "android.permission.WRITE_SETTINGS";
int res = getContext().checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
said "PERMISSION_DENIED" , but it's really changed the ringtone ! If you not believe this, please try by yourself, and you can see from the setting - ring and vibrate - ringtone , you can see the result.
3. After several times try, I figure it out now... both way(manual and auto set by code "setMyRingtone()") of set the ringtone will work on the phone if have the permission of "Settings.System.canWrite(this)", but only work for the Ringtone of SIM 1, not work for SIM2. you can see the result form the setting page(only the ringtone for sim1 will change). if the ringtone still play the default ring of system, the problem probably is the metter of URI .
4. Before I post this thread, both way won't change the result of ringtone from the setting page of the phone, but as I said , you can see the result form another third part application.(this problem most probably is that I only use one SIM card at that time, did I put it into sim2? I don't know, already forget... but now if I put it into sim2 the ringtone form the setting page of the phone never change, but from the log of the code you can see the result is correct actually.)
5. Now the problem change into "How to create a standard URI and how to change the ringtone for SIM2". I will try to work on it.
6. Sorry for my pool English, and sorry for the "messy" code, I will improve it.
Anyway , thank you. you r the only one who helped me... Wish u luck.
Cooper.G said:
6. Sorry for my pool English, and sorry for the "messy" code, I will improve it.
Click to expand...
Click to collapse
I had the ringtone added on my MediaProvider but not set as the current one, I believe AOSP and TW deving is different.
When I mentioned "messy" I meant just copying and pasting the code into the forum, use
Code:
tags next time so it formats perfectly! :good::highfive:
nicholaschum said:
I had the ringtone added on my MediaProvider but not set as the current one, I believe AOSP and TW deving is different.
When I mentioned "messy" I meant just copying and pasting the code into the forum, use
Code:
tags next time so it formats perfectly! :good::highfive:
Click to expand...
Click to collapse
Thank you !
Cooper.G said:
Thank you for your patient.
1. I tried your code, and I was wrong about the permission, it says PERMISSION_DENIED. but I think this is not the problem for this question.
2. Did you tried my code ? The way that I asked for "WRITE_SETTINGS" is really work for ringtone, altho
Java:
private boolean checkWriteSettingsPermissions() {
String permission = "android.permission.WRITE_SETTINGS";
int res = getContext().checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
said "PERMISSION_DENIED" , but it's really changed the ringtone ! If you not believe this, please try by yourself, and you can see from the setting - ring and vibrate - ringtone , you can see the result.
3. After several times try, I figure it out now... both way(manual and auto set by code "setMyRingtone()") of set the ringtone will work on the phone if have the permission of "Settings.System.canWrite(this)", but only work for the Ringtone of SIM 1, not work for SIM2. you can see the result form the setting page(only the ringtone for sim1 will change). if the ringtone still play the default ring of system, the problem probably is the metter of URI .
4. Before I post this thread, both way won't change the result of ringtone from the setting page of the phone, but as I said , you can see the result form another third part application.(this problem most probably is that I only use one SIM card at that time, did I put it into sim2? I don't know, already forget... but now if I put it into sim2 the ringtone form the setting page of the phone never change, but from the log of the code you can see the result is correct actually.)
5. Now the problem change into "How to create a standard URI and how to change the ringtone for SIM2". I will try to work on it.
6. Sorry for my pool English, and sorry for the "messy" code, I will improve it.
Anyway , thank you. you r the only one who helped me... Wish u luck.
Click to expand...
Click to collapse
Hey Have you found the solution..?