I am developing tvos app. I want to display tweets of famous personality like Barack Obama, actors etc. I will get hash tag url from my client. Since, apple tv don't support the webview, I need to call twitter api, parse response and display tweets in my customized UI.

My Queries are: 1. Should I use Rest Api or Streaming Api for this? 2. Do I need to create app on https://apps.twitter.com/app/new and get the keys? 3. Is authentication required as I am just going to display feeds/tweets? 4. Could you please provide some docs or sample app link for apple tv to help as I am totally new to use twitter?

Please guide.

Thanks, Bhavya

As CGRectMake is not available in swift 3.0 and migrator did not convert it i need to manually replace it and it is used more than 300 times in my code so can anyone help me in this to develop regular expression so i can find and replace code. What i want to do is to convert

CGRectMake(a,a,a,a) here a is some value.

to

CGRect(x: a, y: a, w: a, h: a)

func downloadProgress(bytesRead: Int64, totalBytesRead: Int64,
    totalBytesExpectedToRead: Int64) {
    let percent = Float(totalBytesRead)/Float(totalBytesExpectedToRead)

    dispatch_async(dispatch_get_main_queue(), {
        self.progress.setProgress(percent,animated:true)   
    })
    print("Progress´╝Ü\(percent*100)%")
}

func downloadResponse(request: NSURLRequest?, response: NSHTTPURLResponse?,
    data: NSData?, error:NSError?) {
    if let error = error {
        if error.code == NSURLErrorCancelled {
            self.cancelledData = data 
        } else {
            print("Failed to download file: \(response) \(error)")
        }
    } else {
        print("Successfully downloaded file: \(response)")
    }
}

@IBAction func continueBtnClick(sender: AnyObject) {
    if let cancelledData = self.cancelledData {
        self.downloadRequest = Alamofire.download(resumeData: cancelledData,
            destination: destination)

        self.downloadRequest.progress(downloadProgress) 

        self.downloadRequest.response(completionHandler: downloadResponse) 

        self.stopBtn.enabled = true
        self.continueBtn.enabled = false
    }
}

The codes works fine on Alamofire 3.1, but it refuse to work after upgrading to Swift 3.0 and Alamofire 4.0.

The following two line shows error "no such memeber fo progress" and " no such member of response"

  1. self.downloadRequest.progress(downloadProgress)
  2. self.downloadRequest.response(completionHandler: downloadResponse)

How can I solve these two problems?

Thanks.

My app has four tabs that displays different information.

In my second tab view controller i have one button lets name it as button1 in that button1 action i have navigated to SignInViewController screen and in my third tab view controller is loginViewController.

Here purpose of both SignInViewController and loginViewController screen is same i.e.,user can logged into the app in both the ViewController's.

Here what i want exactly is, if I am logged in SignInViewController then whenever I tap on third TabBarItem View Controller should directly navigated to next screen of loginViewController i.e.,to that next screen i have named it as AccountViewController. I have tried below code in tabbarcontroller class but its does not working.

Please help me on this.Thanks in Advance.

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{

       if (tabBarController.selectedIndex == 2){

        {

          if (![[[NSUserDefaults standardUserDefaults]objectForKey:@"SigninStatus"] isEqualToString:@"SigninSuccess"]){

                UIStoryboard *story =  [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                LoginViewController *logInVc = [story instantiateViewControllerWithIdentifier:@"LoginViewController"];
                [self.navigationController pushViewController:logInVc animated:YES];
            }
            else
            {

                UIStoryboard *story =  [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                AccountViewController *accountVc = [story instantiateViewControllerWithIdentifier:@"AccountViewController"];
                [self.navigationController pushViewController:accountVc animated:YES];

            }
        }
    }  
}

How do I access Images from a folder located in Assets.xcassets in Xcode? I know how to access images located in the Assets.xcassets folder itself, but not sure how to access stuff from a specific folder located in Assets.xcassets.

I am using the following code to access images from the Assets.xcassets:

// seperate file for image data containing a struct 
    struct Images {
    var images: [UIImage] = [UIImage(named: "image1.jpg")!]
}

// creating an instance of the image data swift file struct in view controller file  
    var myImages = Images() 

// setting the image property of UIImage in storyboard 
    UImageInstance.image = Images.images[1]

How do I access the images if they are stored in a folder inside Assets.xcassets? instead of just being in Assets.xcassets.

Since migrating to Swift 3.0 on this line :

let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: Selector())

I have the error Cannot invoke initializer for type 'Selector' with no arguments. What am I doing wrong here?

We're trying to solve an issue where we need to detect when a "device" from the perspective from our app is actually a different one.

I was wondering if this was persisted to iCloud and iTunes backups, or if it is re-generated on device change?

I have developed one project in Swift 2.2 and after Swift 3 launch I need to convert it in Swift 3 and make compilable with iOS 10. But after converting the project i face some issue like when I clicked on button which connected with storyboard my application is crash with give reason unrecognized selector sent to instance . It is working in swift 2.2 and i have not change any thing.

 @IBAction func btnTwitter_Clicked(sender:UIButton)
         {
              if checkInternetConnection()
              {
                    SINGLETON.startLoadingActivity(self.view);
                    let objLocationTracker = LocationTracker.sharedInstance
                    objLocationTracker.fetchCurrentLocation({ (objLocation) -> (Void) in
                        SINGLETON.stopLoadingActivity(self.view)
                        self.loginWithTwitter(objLocation: objLocation)
                        })
              }
              else
              {
                 SINGLETON.toast(read_Localizable("noInternet"),view: self.view)
              }
         }

I have been working with RecyclerView for a while. I am following lazy loading, so I am showing 10 data on the view each time. If user scroll to the bottom, the page re-load from the TOP! however, I want to stay where it was previously! So, I have tried to use

recyclerView.scrollToPosition(position);

However, this breaks the UI flow! My second try is using onSaveInstanceState() and onRestoreInstanceState(Bundle state); However, that does not work! My page is re-loads to the top!

Parcelable state = layoutManager.onSaveInstanceState();
layoutManager.onRestoreInstanceState(state);

I have tried every other methods, apparently none is working for me! Any help would be highly appreciated! Thanks in advance!

My Xml code:

<Button
    android:id="@+id/link_btn"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/google_btn" />

I am applying Default ripple effect

<Button
    android:id="@+id/link_btn"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/selectableItemBackground" />

but I need button background "@drawable/google_btn" with
"?android:attr/selectableItemBackground". it's means i need ripple effect with custom background.

My floating button image looks like this

Its a smaller button inside a larger circle, How do I fix this?

layout file:

 <android.support.design.widget.FloatingActionButton
    android:id="@+id/addToKitchenButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="16dp"
    android:layout_gravity="bottom|end"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:src="@drawable/ic_add_circle_black_50dp"
    />

vector code:

  <vector android:height="50dp" android:viewportHeight="24dp"
    android:viewportWidth="24dp" android:width="50dp" xmlns:android="http://schemas.android.com/apk/res/android">

    <path android:fillColor="#FF000000" android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM17,13h-4v4h-2v-4L7,13v-2h4L11,7h2v4h4v2z"/>

</vector>

hi i'm using mapbox to display map in android app. I'm stuck in a situation where I need to get radius of a map that is visible to the user. if user zoomin or zoomout the radius of the map changes. Can anyone tell me how do I do this. or suggest me any reference link regarding this

I am learning to develop android mobile apps. I made a simple app to send a sms. I am using the ADB emulator running marshmallow. I have read about it new permissions here and found lots of questions with answers to my problem with no resolve.

When I do a CLEAN and BUILD I am greeted with the following message:

Error:Gradle: java.io.FileNotFoundException: C:Examples\MySMSApplication\app\build\intermediates\res\resources-debug.ap_ (Access is denied)

Note: I am able to successfully build and run the app when I remove the "uses-permission android:name="android.permission.SEND_SMS". However, I will always get my message "Permission denied" when attempting to send a SMS to say another emulator number 5554.

I have the Android manifest with the two user-permissions set.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.fisher.app">
    <uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/mysmsapp"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

Then in the mainActivity

public class MainActivity extends AppCompatActivity {

    Button buttonSend;
    EditText textPhoneNo;
    EditText textSMS;

    private static final int PERMISSION_REQUEST = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonSend = (Button) findViewById(R.id.buttonSend);
        textPhoneNo = (EditText) findViewById(R.id.editTextPhoneNo);
        textSMS = (EditText) findViewById(R.id.editTextSMS);

        buttonSend.setOnClickListener(new View.OnClickListener() {
            //this is the onclick listener of send button
            @Override
            public void onClick(View v) {
                String phoneNo = textPhoneNo.getText().toString();
                String sms = textSMS.getText().toString();

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (checkSelfPermission(Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
                        if (shouldShowRequestPermissionRationale(Manifest.permission.SEND_SMS)) {
                            Snackbar.make(findViewById(R.id.myView), "You need to grant SEND SMS permission to send sms",
                                    Snackbar.LENGTH_LONG).setAction("OK", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    requestPermissions(new String[]{Manifest.permission.SEND_SMS}, PERMISSION_REQUEST);
                                }
                            }).show();
                        } else {
                            requestPermissions(new String[]{Manifest.permission.SEND_SMS}, PERMISSION_REQUEST);
                        }
                    } else {
                        sendSMS(phoneNo, sms);
                    }
                } else {
                    sendSMS(phoneNo, sms);
                }
            }
        });
    }

    private void sendSMS(String phoneNo, String message) {
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNo, null, message, null, null);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            Snackbar.make(findViewById(R.id.myView), "Permission Granted",
                    Snackbar.LENGTH_LONG).show();
            sendSMS(textPhoneNo.getText().toString(), textSMS.getText().toString());

        } else {

            Snackbar.make(findViewById(R.id.MyView), "Permission denied",
                    Snackbar.LENGTH_LONG).show();

        }
    }
}

Here is the Gradle Build for ref:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.example.fisher.myapp"
        minSdkVersion 23
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.1.1'
}

Here is my code

1.Java Code

class makePOST extends AsyncTask<String, Void, Double> {
    int duration = Toast.LENGTH_SHORT;
    @Override
    protected void onPreExecute() {
        Toast.makeText(update.this, "onPreExecute", Toast.LENGTH_LONG).show();
    }
    protected Double doInBackground(String... params) {
            try {
                url = new URL("http://student.96.lt/Android/update.php");
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setRequestMethod("POST");
                String postdat = "code" + "=" + URLEncoder.encode(mCode, "UTF-8") + "&" + "latitude" + "=" + URLEncoder.encode(mLatitudeText, "UTF-8") + "&" + "longitude" + "=" + URLEncoder.encode(mLongitudeText, "UTF-8");
                //String postdat=mLatitudeText;
                conn.setFixedLengthStreamingMode(postdat.getBytes().length);
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                OutputStream OS = conn.getOutputStream();
                InputStream in = conn.getInputStream();

                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
                bufferedWriter.write(postdat);
                bufferedWriter.flush();
                // Get output
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                    sb.append("\n");
                }

                in.close();
                bufferedWriter.close();
//            java.io.BufferedOutputStream out = new java.io.BufferedOutputStream(conn.getOutputStream());
//            PrintStream pstream = new PrintStream(out);
//            pstream.print(postdat);
//            pstream.close();
            } catch (java.net.MalformedURLException ex) {
                //Toast.makeText(this, ex.toString(), duration ).show();
            } catch (java.io.IOException ex) {
                //Toast.makeText(this, ex.toString(), duration).show();
            }
            return null;
        }

    };  

2. PHP Code(update.php)

<?php
include 'connect.php';
$m_lat=$_POST['latitude'];
$m_lng=$_POST['longitude'];
$m_code=$_POST['code'];
$query="update `location` set `longitude`='$m_lng',`latitude`='$m_lat' where `code`='$m_code'";
mysqli_query($connect,$query);
mysqli_close($connect);
?>

3. AndroidManifest.xml File

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.project.nikhil.gpslocation">
<permission
    android:name="com.javapapers.currentlocationinmap.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.javapapers.currentlocationinmap.permission.MAPS_RECEIVE" />
<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" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <uses-feature
        android:name="android.hardware.location.gps"
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="MyKey" />
    <activity
        android:name=".update"
        android:label="@string/title_activity_update"
        android:exported="true"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

And I also want to update longitude and latitude every 10 seconds. This is my First app. I'm at beginning level of android development, Please help me !

Now My php code is working you can check this out at : student.96.lt/Android/test.php

I'm working with android crop image , this is my code for cropping image :

private void performCrop() {
    try {
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        //indicate image type and Uri
        cropIntent.setDataAndType(picUri, "image/*");
        //set crop properties
        cropIntent.putExtra("crop", "true");
        //indicate aspect of desired crop
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        //indicate output X and Y
        cropIntent.putExtra("outputX", 500);
        cropIntent.putExtra("outputY", 500);
        //retrieve data on return
        cropIntent.putExtra("return-data", true);
        //start the activity - we handle returning in onActivityResult
        startActivityForResult(cropIntent, PIC_CROP);
    } catch (ActivityNotFoundException anfe) {
        //display an error message
        String errorMessage = "err";
        Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
        toast.show();
    }
}

I have tested this code on android 4.2 , 4.3 and the was no problem , but on android 5,6 , it's returning null pointer exception and I don't know why .

what is wrong with this code ? how can I make it compatible with all version of android ?

This code is for my splash screen Activity:

    @Override
    protected void onResume() {
    super.onResume();
    handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            Intent intent = new Intent(SplashActivity.this, MainActivity.class);
            startActivity(intent);
        }
    }, 5000);
}

When I click the device back button ,MainActivity become finish and again SplashActivity comes to up,and again it's onResume method get call, problem is here that handler doesn't execute again and MainActivity doesn't start again after 5 second ! I want it execute again!

what's the problem and what should i do?

thanks for attention.

is there any action available to listen audio so that when I say my preset word like "good morning", it should launch my app. It means I want to make a broadcast receiver with the action define 'listen audio' as any one say "good morning" like "Ok google", my receiver should listen this and do my task.

Please help me that will be great. Thank you in advance.

I have ViewPager, couple of pages contain EditText fields. The task is to open soft keyboard on page with first EditText (phone number), after click on Done button switch to another page and set focus on second EditText (verification code). Keyboard must be always opened, EditText field must be above. On second page it got covered.

<android.support.percent.PercentFrameLayout
    android:id="@+id/verification"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.AppCompatImageView
        android:id="@+id/superup_logo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        app:layout_marginTopPercent="33%"
        app:layout_widthPercent="65%"
        app:srcCompat="@drawable/animated_superup_logo_white"/>

    <superup.onboarding.NonSwipeableViewPager
        android:id="@+id/verifyPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/transition">

        <android.support.percent.PercentRelativeLayout
            android:id="@+id/layout_start"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <android.support.v7.widget.AppCompatImageView
                android:id="@+id/superup_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                app:layout_marginTopPercent="67%"
                app:layout_widthPercent="50%"
                app:srcCompat="@drawable/superup_name"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/superup_name"
                android:layout_centerHorizontal="true"
                android:text="@string/layout_start_text"
                android:textColor="@color/white"
                android:textSize="18dp"
                android:textStyle="bold"/>

        </android.support.percent.PercentRelativeLayout>

        <android.support.percent.PercentRelativeLayout
            android:id="@+id/layout_number"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layoutDirection="ltr">

            <TextView
                android:id="@+id/txt_number"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:gravity="center"
                android:text="@string/layout_number_text"
                android:textColor="@color/white"
                android:textSize="18dp"
                android:textStyle="bold"
                app:layout_marginTopPercent="3%"/>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:gravity="center"
                app:layout_marginBottomPercent="23%"
                app:layout_widthPercent="75%">

                <superup.onboarding.CountryCodePicker
                    android:id="@+id/country_code"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    app:contentColor="@color/white"
                    app:countryPreference="IL"
                    app:defaultNameCode="IL"
                    app:hideNameCode="true"
                    app:textSize="24sp"/>

                <EditText
                    android:id="@+id/et_number"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:digits="1234567890"
                    android:gravity="center"
                    android:imeOptions="actionDone"
                    android:inputType="number"
                    android:maxLength="10"
                    android:textColor="@color/white"
                    android:textSize="24sp"/>
            </LinearLayout>

        </android.support.percent.PercentRelativeLayout>

        <android.support.percent.PercentRelativeLayout
            android:id="@+id/layout_otp"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <superup.onboarding.PinEntryEditText
                android:id="@+id/et_code"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:cursorVisible="false"
                android:digits="1234567890"
                android:imeOptions="actionDone"
                android:inputType="number"
                android:maxLength="4"
                android:textIsSelectable="false"
                android:textSize="50dp"
                android:textStyle="bold"
                app:layout_marginBottomPercent="23%"
                app:layout_marginLeftPercent="20%"
                app:layout_marginRightPercent="20%"/>

            <TextView
                android:id="@+id/txt_wrong"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_above="@+id/et_code"
                android:layout_centerHorizontal="true"
                android:padding="10dp"
                android:text="@string/wrong_number"
                android:textColor="@color/white"
                android:textSize="16dp"
                android:textStyle="bold"/>

            <TextView
                android:id="@+id/txt_phone"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_above="@+id/txt_wrong"
                android:layout_centerHorizontal="true"
                android:layoutDirection="ltr"
                android:textColor="@color/white"
                android:textSize="20dp"
                android:textStyle="bold"/>

        </android.support.percent.PercentRelativeLayout>

    </superup.onboarding.NonSwipeableViewPager>

</android.support.percent.PercentFrameLayout>

With page swipe it works perfect, but i need to switch pages with keyboard. After changing page with verifyPager.setCurrentItem EditText is covered with keyboard over it.

et_number.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
            switch (actionId) {
                case EditorInfo.IME_ACTION_DONE:
                    verifyPager.setCurrentItem(verifyPager.getChildCount() - 1);
                    return true;
                default:
                    return false;
            }
        }
    });

Samsung with Android 6 has this bug, Nexus 5X/6P/Asus don't.

I have a wordpress woocommerce site and an android mobile app. I want to integrate wordpress site and android app. I want to login and register from android app into wordpress site. then I also sell product by this app.

I'm trying to develop a service that whenever an user opens an app my service will identify it. I'm using the files: /proc/[pid]/cgroup,/proc/[pid]/cmdline,/proc/[pid]/oom_score,/proc/[pid]/oom_score_adj to check if it's an user app running on foreground. Actually it's working but when I try to open any game the service won't recognize it all the time. (The service only identify the files (oom_score) that has the lowest value).

Example: oom_score for "com.google.android.googlequicksearchbox:interactor" is 75, but for "com.king.candycrushsaga" will be >150, so it will never be detected by the code (as it follows).

Service code:

scheduler.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        s=appManager.getAppRunningForeground();
        System.out.println(s);
    }
},1,2,SECONDS);

Function that gets the app running:

private ReadWriteFile readWriteFile = new ReadWriteFile();
public String getAppRunningForeground(){
    int pid;
    File[] files = new File("/proc").listFiles();
    int lowestOomScore = Integer.MAX_VALUE;
    String foregroundProcess = null;
    for (File file : files) {
        if (!file.isDirectory() || (!file.getName().matches(("\\d+"))))
            continue;
        pid = Integer.parseInt(file.getName());
        try {
            String cgroup = readWriteFile.read(String.format("/proc/%d/cgroup", pid));
            String[] lines = cgroup.split("\n");
            if (lines.length != 2)
                continue;
            String cpuSubsystem = lines[0];
            String cpuaccctSubsystem = lines[1];
            if (!cpuaccctSubsystem.endsWith(Integer.toString(pid)) || cpuSubsystem.endsWith("bg_non_interactive"))
                continue;
            String cmdline = readWriteFile.read(String.format("/proc/%d/cmdline", pid));
            if (cmdline.contains("com.android.systemui")||cmdline.contains("com.google.android.googlequicksearchbox:interactor")) {
                continue;
            }
            int uid = Integer.parseInt(cpuaccctSubsystem.split(":")[2].split("/")[1].replace("uid_", ""));
            if (uid > 1000 && uid <= 1038)//System process
                continue;
            File oomScoreAdj = new File(String.format("/proc/%d/oom_score_adj", pid));
            if (oomScoreAdj.canRead()) {
                int oomAdj = Integer.parseInt(readWriteFile.read(oomScoreAdj.getAbsolutePath()));
                if (oomAdj != 0) {
                    continue;
                }
            }
            int oomscore = Integer.parseInt(readWriteFile.read(String.format("/proc/%d/oom_score", pid)));
            if (oomscore < lowestOomScore) {
                lowestOomScore = oomscore;
                foregroundProcess = cmdline.replaceAll("\\p{Cntrl}", "");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return foregroundProcess;
}

Class that reads a file.

public class ReadWriteFile{
    File file;
    StringBuilder teste3 = new StringBuilder();
    FileOutputStream outputStream;
    public static String read(String path) throws IOException {
        StringBuilder output = new StringBuilder();
        BufferedReader reader = new BufferedReader(new FileReader(path));
        output.append(reader.readLine());
        for (String line = reader.readLine(); line != null; line = reader.readLine())
            output.append('\n').append(line);
        reader.close();
        return output.toString();
    }
}

P.S: getRunningTasks is deprecated, so please, don't suggest it.

I just wanna know when jvm runs test cases is that they generate .class files for it in both simple java program or android program.