jeudi 13 août 2015

Can someone help me with aidl while using android:process?

I wrote an aidl service and set android:process=".remote" in AndroidManifest, but I can only get the original data and while the data updated, the data I get doesn't change. But while I delete the android:process it works. Why did this happen and how does android:process works?

for example: aidl:

interface ILoginInfoService {
    String getLoginInfo();
}

TestService:

public class TestService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
    private final ILoginInfoService.Stub mBinder = new ILoginInfoService.Stub() {
        @Override
        public String getLoginInfo() throws RemoteException {
            return TestClass.string;
        }
    };
}

TestClass:

public class TestClass {
    static String string = "a";
}

TestActivity:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        TestClass.string += "a";
        try {
            if(mRemoteService.getLoginInfo() != null) {
                textView.setText(mRemoteService.getLoginInfo());
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
});

it only shows "a" while i click the button, but if i delete the android:process below ,the string will increase("a", "aa", "aaa", ...).

<service android:name=".TestService" android:process=".remote">
    <intent-filter>
        <action android:name="com.example.chayne_shen.testservice.TestService" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</service>



via Chebli Mohamed

Android transparent status bar implementation?

I noticed Play Store application detail pages show a transparent status bar since version 5.4, but how is it implemented?

I tried to add WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS flag to my window, but the result is both the status bar and the navigation bar are transparent. How can I just make the status bar transparent but the navigation bar keeps normal?



via Chebli Mohamed

AsyncTask that can show progress when synchronous, execute().get()

Another Android puzzler. Sure someone has an answer, but I can't figure it out. Here's the scenario and then I will show some code...

I have a list of data (call them "Forms") I want to submit to our servers. Each of these "Forms" can have media associated with them, the task is syncPendingFormsResultTask. On top of that, sometimes as I am submitting the "Form" I may have to prompt the user for more information before submitting it. That prompting requires me to get more info, right at that moment, from the server...another AsyncTask call, workflowTask.

My problem is showing progress and also gathering the data. The tendency is for the Dialogs prompting for more data to display last and for no progress dialog information to be shown. It works fine for a single instance, so I know it must be AsyncTask related (not the first time there!).

The logic is something like this:

Loop forms

 if (more data)
     AsyncTask get more data (synchronous using .get())
     Dialog to prompt user with data from AsyncTask 
         AsyncTask to submit gathered data, show progress progress of media
             being sent to server
 else 
     AsyncTask to submit gathered data, show progress of media being sent to
             server

Please note that in the onClick in the promptUserForWorkflowInfo the same AsyncTask syncPendingFormsResultTask to submit data is called. I have tried to make the syncPendingFormsResultTask synchronous (using execute().get()) without success.

Bottom line is that I would like this all to really be synchronous and to display the progress...for example with 3 "Forms" and 1 needing extra data it would:

Form 1 (no data needed)...sending 1 of 3 media
Form 1 (no data needed)...sending 2 of 3 media
Form 1 (no data needed)...sending 3 of 3 media
Form 2 - Getting extra data from server...
Form 2 - Prompt user for more data
Form 2 (extra data)    ...sending 1 of 3 media
Form 2 (extra data)...sending 2 of 3 media
Form 2 (extra data)...sending 3 of 3 media
Form 3 (no data needed)...sending 1 of 3 media
Form 3 (no data needed)...sending 2 of 3 media
Form 3 (no data needed)...sending 3 of 3 media

Everything does seem to submit fine, just not getting progress or prompting for data in order shown.

Code:

         Integer cnt = 1;
         Integer size = pendingForms.size();
         for (FormSimple pendingForm : pendingForms) {

             Form form = libraryUtils.retrieveFormInstanceForm(pendingForm.getInstanceId());

             if (form.getWorkflow() != null) {
                 // before we submit, check to see if we need to get workflow info
                 ArrayList<WorkflowInfo> workflowinfo = null;
                 try {
                     workflowinfo = new workflowTask().execute(form).get();
                     promptUserForWorkflowInfo(getActivity(), form, workflowinfo, size, cnt);
                 }
                 catch (Exception ex) {
                     Utilities.logException(ex);
                 }
             }
             // Just submit
             else {
                 new syncPendingFormsResultTask().execute(form, size, cnt); 
             }

             // Increment count
             cnt++;
         }                   

Finally, I have also tried to



via Chebli Mohamed

How to layout a RelativeLayout in a custom view's onLayout function?

I am implementing a custom view, and I have three subviews that I can't get to appear. It seems like the subviews aren't showing; I have set the backgrounds to be red, blue, and green for now to show where I have made set the layout, which is shown in the picture.

I need the subviews to be shown so that the view is complete.

This is the code I'm using in onLayout for the subviews:

    backButton.layout(leftOffset, topOffset, leftOffset + seventhWidth, topOffset + seventhWidth);
    backButton.setBackgroundColor(Color.RED);
    nextButton.layout((int) (leftOffset + calendarWidth - seventhWidth), topOffset, (int) (leftOffset + calendarWidth), topOffset + seventhWidth);
    nextButton.setBackgroundColor(Color.GREEN);
    monthContainerLayout.layout(leftOffset + thirdWidth, topOffset, (int) Math.round(leftOffset + 2 * thirdWidth), topOffset + seventhWidth);
    monthContainerLayout.setBackgroundColor(Color.BLUE);

This is the layout XML for the red square:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    android:id="@+id/back"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:src="@drawable/back_icon"
        android:layout_width="wrap_content"
        android:layout_height="@dimen/icon_height" />

</RelativeLayout>

This is what the code and layout currently produces (my custom view is only the calendar):

enter image description here



via Chebli Mohamed

How to get app's metadata from another app?

I am trying to add a feature to my app which receives broadcast data from Spotify and does something with that data. However, I am not sure how to proceed. I've been able to piece together the following code with the help of previous questions, however those questions do not go into detail on how to actually initiate the reception of data. I have a BroadCast Receiver:

<receiver
        android:name=".Receiver"
        android:enabled="true"
        android:exported="true">

        <intent-filter>
            <action android:name="com.spotify.music.playbackstatechanged"/>
            <action android:name="com.spotify.music.metadatachanged"/>
            <action android:name="com.spotify.music.queuechanged"/>
        </intent-filter>

    </receiver>

I have a BroadCast Receiver class (all set up):

public class Receiver extends BroadcastReceiver {

static final class BroadcastTypes {
    static final String SPOTIFY_PACKAGE = "com.spotify.music";
    static final String PLAYBACK_STATE_CHANGED = SPOTIFY_PACKAGE + ".playbackstatechanged";
    static final String METADATA_CHANGED = SPOTIFY_PACKAGE + ".metadatachanged";
}


@Override
public void onReceive(Context context, Intent intent) {

    long timeSentInMs = intent.getLongExtra("timeSent", 0L);
    String action = intent.getAction();

    if (action.equals(BroadcastTypes.METADATA_CHANGED)) {

        String trackId = intent.getStringExtra("id");
        String artistName = intent.getStringExtra("artist");
        String albumName = intent.getStringExtra("album");
        String trackName = intent.getStringExtra("track");
        int trackLengthInSec = intent.getIntExtra("length", 0);

        //send data to main class?

    } else if (action.equals(BroadcastTypes.PLAYBACK_STATE_CHANGED)) {

        boolean playing = intent.getBooleanExtra("playing", false);
        int positionInMs = intent.getIntExtra("playbackPosition", 0);

        //send data to main class?
    }

  }
}

and I have a main Activity class. So now I am not sure how I can actually start the acquisition of data from Spotify in my main activity, or how to then send that data (from the receiver) back to my main activity for later use.

Thanks for any advice



via Chebli Mohamed

POST String From Android To Php

I'm having trouble posting a String from android to php. I'm trying to post a username since I was to exclude the current users username from the query. In Java I have an AsyncTask with the code below in the doInBackground(String... params)

ArrayList<NameValuePair> data_to_send = new ArrayList<>();
    data_to_send.add(new BasicNameValuePair("Username", username));

    HttpParams httpRequestParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpRequestParams, ServerRequests.CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpRequestParams, ServerRequests.CONNECTION_TIMEOUT);


    HttpClient client = new DefaultHttpClient(httpRequestParams);
    HttpPost post = new HttpPost(ServerRequests.SERVER_ADDRESS + "TestQuery.php");

    try {
        post.setEntity(new UrlEncodedFormEntity(data_to_send));
        client.execute(post);
    } catch (Exception e) {

        e.printStackTrace();
    }

And this is in my php:

$origLat = 45.6215349;
$origLon = 18.6951613;
$dist = 30; 
$username = $_POST["Username"];

$sql = "SELECT ID, Username, Name, Age, City, Gender, Latitude, Longitude, 3956 * 2 * 1.609344 * 1000 *
      ASIN(SQRT( POWER(SIN(($origLat - abs(Latitude))*pi()/180/2),2)
      +COS($origLat*pi()/180 )*COS(abs(Latitude)*pi()/180)
      *POWER(SIN(($origLon-Longitude)*pi()/180/2),2))) 
      as distance FROM users WHERE Username != '$username'
      AND Longitude BETWEEN ($origLon-$dist/abs(cos(radians($origLat))*69)) 
      AND ($origLon+$dist/abs(cos(radians($origLat))*69)) 
      AND Latitude BETWEEN ($origLat-($dist/69)) 
      AND ($origLat+($dist/69))
      HAVING distance < $dist ORDER BY distance limit 30;"; 

Well the query works when I input the String directly by changing the Username != 'Jawe' but I'm not sure why it doesn't work when posted from Android. Anyone know the problem?



via Chebli Mohamed

Accessing model data from fragments of viewpager

I'm currently writing an app that displays cooking recipes when clicked.

My data is stored in a custom content provider and the information for my recipes is stored in 3-4 tables.

DetailActivity contains a Fragment(Let's call is MasterFragment).

MasterFragment contains a ViewPager which holds 3 fragments that display the main parts of my model: general info, ingredients and directions. Let's call them GeneralFragment, IngredientFragment and DirectionFragment.

How it stands now, the 3 fragments of the ViewPager all receive the appropriate Uri and each has a loader that loads the data from the content provider and displays it in my UI.

My problem is that having the data loaded into the 3 fragments adds a lot of complexity to my code when it comes to updating the data in the content provider. On top of that, I feel like that doing in this manner may not be the most efficient way of fetching and displaying my data.

One alternative that I thought of was to query all the data in my MasterFragment and to pass it to each individual fragment of the ViewPager through the its adapter. Once again, this is a hassle that requires a lot of overhead and may not be optimal.

I'm thinking that the best way of doing it may be to centralize the model data into the MasterFragment and have the fragments access that data. I'm just not sure how to implement this. I'm leaning towards using a singleton recipe class but I'd rather here your opinion before implementing it.

I'd appreciate any input and I thank you in advance for your time.

tl;dr: Model needs to be accessed by 3 fragments in a viewpager, what is the best way of doing this?



via Chebli Mohamed