#StackBounty: #android #reactjs #leaflet map does not react to touch when there is scroll bar

Bounty: 150

I’m using android, and why is that when there is a scroll bar, the map is not reacting fluidly to the touch events. I’m trying to drag the map but the whole page is scrolling up. How do we make it in a way that when we drag inside the map, only the map container will respond to touch events?

If there is no scrollbar / only leaflet is in the screen, the map pans/drag gracefully.enter image description here

PS: I have tried setting tap:false in map options, but it doesn’t work. I am using leaflet 1.0.3

Example code:

MainForm component

  <Container>
                <Header>
                <Title>Main</Title>
                </Header>
                <Content>
                <TestWV />
                <Grid>
                    <Col style={{ height: 700, 
                                    justifyContent: 'center',
                                    alignItems: 'center', }}
                    >
                        <Row size={1} >
                            <TouchableOpacity onPress={this.onMiniApp1Press.bind(this)}>
                                <Thumbnail square size={100} source={oneminute} 
                                />
                            </TouchableOpacity>
                        </Row>
                        <Row size={1} >
                        </Row>
                    </Col>
                    <Col style={{ height: 700, 
                                    justifyContent: 'center',
                                    alignItems: 'center', }}
                    >
                        <Row size={1} >
                            <TouchableOpacity>
                                <Thumbnail square size={100} source={pakipoo} 
                                />
                            </TouchableOpacity>
                        </Row>
                        <Row size={1} >
                        </Row>
                    </Col>
                </Grid>
                </Content>
            </Container>

TestWV component

     <View>
     <WebView
        source={{uri: 'http://yahoo.com'}}
        javaScriptEnabled={true}
        domStorageEnabled={true}
        startInLoadingState={true}
        style={{ height: 500, flex: 1 }}

        >
    </WebView>
    </View>


Get this bounty!!!

#StackBounty: #android #android-studio #kotlin Android Studio 3.0 Preview Messing Imports when refactoring Kotlin code

Bounty: 50

Whenever I try to refactor Koltin code on Android Studio 3.0 it simply removes all my “top level” imports and starts using “inplace” imports.

By refactorying I mean, in this case, moving code around. So let’s say I have a class under com.myapp package. If I move it to com.myapp.anotherpackage this issue happens

Funny fact about this, looks like it only happens when you move more than one file at the same thime

What it looks like:

//Before refactoring I have this import
import android.support.v7.app.AppCompatActivity;

class MyActivity : AppCompatActivity() {
    //code
}

Then after refactoring it goes like this

//"top level" import is gone

class MyActivity : android.support.v7.app.AppCompatActivity() { //"inline" import
    //code
}

enter image description here

It gets even worse if I have to refactor the code again, as every single import is “inlined”, android studio doesn’t refactor those, and I have to do fix them by hand. This is getting really annoying already, as I had to fix over 100 of these. Any thoughts on how to fix this?


Get this bounty!!!

#StackBounty: #android #web-apps #information-management #crm Personal Relationship Managment or CRM

Bounty: 50

I’m looking for a personal CRM kind of system. Only usually CRM is aimed for business and sales. I just like to keep information about people in one place. For example I know people in industry that I speak from time to time and I’d like to keep some personal relevant information close at hand – like ages of kids, wife’s place of work, other tidbits that you usually forget after a while.
I.e. I’m planning to call Mr Smith, so I can quickly look up personal info about Mr. Smith and ask how’s his kids are getting on in school and remind myself their names and ages.

It’s nice to have people remembering irrelevant information about you. I’d like to remember this kind of stuff about people I interact with.

I’ve tried a few CRMs but they are all business oriented. Is there anything out there that can help me?

Ideally it should work on Android and through Web, be able to hook into social media and do search by name.

P.S. It does not have to be free. I’m ready to pay a reasonable monthly fee for this service


Get this bounty!!!

#StackBounty: #android #ubuntu #password-manager #wifi How to store online/in cloud WIFI passwords?

Bounty: 100

I’m using Ubuntu, and I need a password manager that stores automatically wifi ESSIDs/passwords (such as wap keys) as I save them.
Moreover, it should be import all wifi keys already saved.
Everything should be stored online and accessible from an Android app.

LastPass doesn’t work with WIFI passwords (not on Ubuntu, unfortunately).

If you can suggest one such software, please provide documentation for my specific request.


Get this bounty!!!

#StackBounty: #audio #java #android #audio-playback #android-things How can I get audio (ultrasonic Nearby API) working with Android Th…

Bounty: 50

I’m trying out Android Things on my Raspberry Pi 3, and besides a little bit of a learning curve around the adb utility, things are going well. However, it doesn’t seem like audio is working at all.

Ultimately I’m writing a small app using Google’s Nearby API. This allows one Android device (my Pi) to talk to another over a short range. It does this over wifi and bluetooth. It also has an option to communicate over an extremely short range by using the speakers and microphone of the respective devices and sending near-ultrasonic sounds. I verified that the normal version (i.e. wifi/bluetooth) of Nearby is working correctly on my Pi. That is, I can publish a message from the Pi, and receive it on my phone. Again, that is working.

However, when I switch the publish strategy to “earshot,” which uses the near-ultrasonic sounds, then my phone can no longer seem to see the signal coming from the Pi. So, I ran a test just to see if the audio was working at all, by adding a short bit of code to my app to play an MP3 file:

MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.test_audio);
mediaPlayer.start();

But I don’t hear anything. When I run the application in an Android emulator, the sound plays. But when I move it onto the Raspberry Pi, it won’t play anything. This would explain why the ultrasonic signals from the Nearby API aren’t working. I tested this using both the HDMI output and the 3.5 mm jack on the Pi and in both cases I could not hear any audio playing.

Does anyone know how to get audio working on a Raspberry Pi running Android Things?


Get this bounty!!!

#StackBounty: #java #android #printing #wifi-direct ANDROID -How to print a text file using WiFi Direct

Bounty: 100

I have a working Android app that displays user stats. I want to send a small report with plain text format (.txt) to a WiFi Direct printer. I have downloaded the sample demo app from Android. I did the proper modification in order to look for .txt file. But I don’t understand why my code is not working. After selecting the file I want to print, nothing happens.

The current configuration for my EPSON printer bellow.

  • Wi-Fi Direct Mode : On

  • Communication Mode: AP

  • Operation Mode: IEEE802.11g/n

  • Communication Speed: Auto

  • SSID: DIRECT-D3A36C54
  • Channel: 7
  • Security Level: WPA2-PSK(AES)

  • Link Status: Unknown

This is the DeviceDetailFragment class

public class DeviceDetailFragment extends Fragment implements WifiP2pManager.ConnectionInfoListener {
    protected static final int CHOOSE_FILE_RESULT_CODE = 20;
    private View mContentView = null;
    private WifiP2pDevice device;
    private WifiP2pInfo info;
    ProgressDialog progressDialog = null;
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContentView = inflater.inflate(R.layout.device_detail, null);
        mContentView.findViewById(R.id.btn_connect).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WifiP2pConfig config = new WifiP2pConfig();
                config.deviceAddress = device.deviceAddress;
                config.wps.setup = WpsInfo.LABEL;
                config.wps.pin = "12345677";
//                config.groupOwnerIntent = 15;
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                progressDialog = ProgressDialog.show(getActivity(), "Press back to cancel",
                        "Connecting to :" + device.deviceAddress, true, true
//                        new DialogInterface.OnCancelListener() {
//
//                            @Override
//                            public void onCancel(DialogInterface dialog) {
//                                ((DeviceActionListener) getActivity()).cancelDisconnect();
//                            }
//                        }
                );
                ((DeviceListFragment.DeviceActionListener) getActivity()).connect(config);
            }
        });
        mContentView.findViewById(R.id.btn_disconnect).setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ((DeviceListFragment.DeviceActionListener) getActivity()).disconnect();
                    }
                });
        mContentView.findViewById(R.id.btn_start_client).setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // Allow user to pick a text file from storage or other
                        // registered apps
                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                        intent.setType("text/*");
//                        intent.setType("image/*");
                        startActivityForResult(intent, CHOOSE_FILE_RESULT_CODE);
                    }
                });
        return mContentView;
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // User has picked a text file. Transfer it to group owner i.e peer using
        // FileTransferService.
        Uri uri = data.getData();
        TextView statusText = (TextView) mContentView.findViewById(R.id.status_text);
        statusText.setText("Sending: " + uri);
        Log.d(WiFiDirectActivity.TAG, "Intent----------- " + uri);
        Intent serviceIntent = new Intent(getActivity(), FileTransferService.class);
        serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
        serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString());
        serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
                info.groupOwnerAddress.getHostAddress());
        serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8315); //631
        getActivity().startService(serviceIntent);
    }
    @Override
    public void onConnectionInfoAvailable(final WifiP2pInfo info) {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        this.info = info;
        this.getView().setVisibility(View.VISIBLE);
        // The owner IP is now known.
        TextView view = (TextView) mContentView.findViewById(R.id.group_owner);
        view.setText(getResources().getString(R.string.group_owner_text)
                + ((info.isGroupOwner == true) ? getResources().getString(R.string.yes)
                : getResources().getString(R.string.no)));
        // InetAddress from WifiP2pInfo struct.
        view = (TextView) mContentView.findViewById(R.id.device_info);
        view.setText("Group Owner IP - " + info.groupOwnerAddress.getHostAddress());
        // After the group negotiation, we assign the group owner as the file
        // server. The file server is single threaded, single connection server
        // socket.
        if (info.groupFormed && info.isGroupOwner) {
            new FileServerAsyncTask(getActivity(), mContentView.findViewById(R.id.status_text))
                    .execute();
        } else if (info.groupFormed) {
            // The other device acts as the client. In this case, we enable the
            // get file button.
            mContentView.findViewById(R.id.btn_start_client).setVisibility(View.VISIBLE);
            ((TextView) mContentView.findViewById(R.id.status_text)).setText(getResources()
                    .getString(R.string.client_text));
        }
        // hide the connect button
        mContentView.findViewById(R.id.btn_connect).setVisibility(View.GONE);
    }
    /**
     * Updates the UI with device data
     *
     * @param device the device to be displayed
     */
    public void showDetails(WifiP2pDevice device) {
        this.device = device;
        this.getView().setVisibility(View.VISIBLE);
        TextView view = (TextView) mContentView.findViewById(R.id.device_address);
        view.setText(device.deviceAddress);
        view = (TextView) mContentView.findViewById(R.id.device_info);
        view.setText(device.toString());
    }
    /**
     * Clears the UI fields after a disconnect or direct mode disable operation.
     */
    public void resetViews() {
        mContentView.findViewById(R.id.btn_connect).setVisibility(View.VISIBLE);
        TextView view = (TextView) mContentView.findViewById(R.id.device_address);
        view.setText(R.string.empty);
        view = (TextView) mContentView.findViewById(R.id.device_info);
        view.setText(R.string.empty);
        view = (TextView) mContentView.findViewById(R.id.group_owner);
        view.setText(R.string.empty);
        view = (TextView) mContentView.findViewById(R.id.status_text);
        view.setText(R.string.empty);
        mContentView.findViewById(R.id.btn_start_client).setVisibility(View.GONE);
        this.getView().setVisibility(View.GONE);
    }
    /**
     * A simple server socket that accepts connection and writes some data on
     * the stream.
     */
    public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
        private Context context;
        private TextView statusText;
        /**
         * @param context
         * @param statusText
         */
        public FileServerAsyncTask(Context context, View statusText) {
            this.context = context;
            this.statusText = (TextView) statusText;
        }
        @Override
        protected String doInBackground(Void... params) {
            try {
                ServerSocket serverSocket = new ServerSocket(8315); //631
                Log.d(WiFiDirectActivity.TAG, "Server: Socket opened");
                Socket client = serverSocket.accept();

                Log.d(WiFiDirectActivity.TAG, "Server: connection done");
//                final File f = new File(Environment.getExternalStorageDirectory() + "/"
//                        + context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
//                        + ".txt");


                final File f = new File(Environment.getExternalStorageDirectory() + "/"
                        + context.getPackageName() + "/wifip2pshared-" + ".txt");
                File dirs = new File(f.getParent());
                if (!dirs.exists())
                    dirs.mkdirs();
                f.createNewFile();
                Log.d(WiFiDirectActivity.TAG, "server: copying files " + f.toString());
                InputStream inputstream = client.getInputStream();
                copyFile(inputstream, new FileOutputStream(f));
                serverSocket.close();
                return f.getAbsolutePath();
            } catch (IOException e) {
                Log.e(WiFiDirectActivity.TAG, e.getMessage());
                return null;
            }
        }
        /*
         * (non-Javadoc)
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */
        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                statusText.setText("File copied - " + result);
//                Log.e("...File copied - ", result);
                Intent intent = new Intent();
                intent.setAction(android.content.Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.parse("file://" + result), "text/*");
                context.startActivity(intent);
            } else {
                Log.e("File copied is NULL- ", result);
            }
        }
        /*
         * (non-Javadoc)
         * @see android.os.AsyncTask#onPreExecute()
         */
        @Override
        protected void onPreExecute() {
            statusText.setText("Opening a server socket");
        }
    }
    public static boolean copyFile(InputStream inputStream, OutputStream out) {
        byte buf[] = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            out.close();
            inputStream.close();
        } catch (IOException e) {
            Log.d(WiFiDirectActivity.TAG, e.toString());
            return false;
        }
        return true;
    }
}


Get this bounty!!!

#StackBounty: #android #android-source #alsa #android-kernel #android-rom Modifying in-call voice playback in Android custom ROM

Bounty: 200

I would like to modify Android OS (official image from AOSP) to add preprocessing to normal phone call playback sound.

I’ve already achieved this filtering for app audio playback (by modifying HAL and audioflinger).

I’m OK with targeting only a specific device (Nexus 5X). Also, I only need to filter playback – I don’t care about recording (uplink).

UPDATE:
To make it clear – I’m OK with modifying Qualcomm specific drivers, or whatever part that runs on Nexus 5X can help me modify in-call playback.

UPDATE #2:

I’m attempting to create a Java layer app that routes the phone playback to the music stream in real time.
I’ve already succeeded in installing it as a system app, getting permissions for initializing AudioRecord with AudioSource.VOICE_DOWNLINK.
However, the recording gives blank samples, it doesn’t record the voice call.

Code inside my worker thread:

// Start recording
        int recBufferSize = AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT);
        mRecord = new AudioRecord(MediaRecorder.AudioSource.VOICE_DOWNLINK, 44100, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT, recBufferSize);

        // Start playback
        int playBufferSize = AudioTrack.getMinBufferSize(44100, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT);
        mTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT, playBufferSize, AudioTrack.MODE_STREAM);

        mRecord.startRecording();;
        mTrack.play();

        int bufSize = 1024;
        short[] buffer = new short[bufSize];
        int res;
        while (!interrupted())
        {
            // Pull recording buffers and play back
            res = mRecord.read(buffer, 0, bufSize, AudioRecord.READ_NON_BLOCKING);

            mTrack.write(buffer, 0, res, AudioTrack.WRITE_BLOCKING);
        }

        // Stop recording
        mRecord.stop();
        mRecord.release();
        mRecord = null;

        // Stop playback
        mTrack.stop();
        mTrack.release();;
        mTrack = null;

I’m running on Nexus 5X, my own AOSP custom ROM, Android 7.1.1.
I need to find the place which will allow call recording to work – probably somewhere in hardware/qcom/audio/hal in platform code.

Also I’ve been looking at:
The function voice_check_and_set_incall_rec_usecase at hardware/qcom/audio/hal/voice.c
But wasn’t able to make sense out of it or how to make it work.


Get this bounty!!!

#StackBounty: #android #animation #scroll #android-tablayout #android-coordinatorlayout CoordinatorLayout + TabView + AnimateView(From …

Bounty: 50

Yesterday I am playing with CoordinatorLayout with TabView

1) What is my target ?

  • CoordinatorLayout with TabView
  • When I scroll up at that time One View As show in .GIF move down.
  • and Stick on the Top of the TabView (inside AppBar).

enter image description here

2) Where I reached ?

  • CoordinatorLayout with TabView with pretty scrolling.
  • TabView with Appbar Stop Scrolling At Top after Then Scroll RecyclerView.

enter image description here

3) Where I stuck ?

  • When I scroll Up One View Scroll Down but TabView Stick At Top not like 1st gif.

4) Code snippet

  • Xml file
    <android.support.design.widget.AppBarLayout
        android:id="@+id/main.appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
        <!--- ADD TAB_LAYOUT HERE -->
    
    
        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/main.collapsing"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll">
    
            <ImageView
                android:id="@+id/main.backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                android:src="@drawable/abc"
                app:layout_collapseMode="none" />
    
    
            <!-- ADD ANY THING THAT GETS SCROLLED ALL THE WAY UP WITH TOOLBAR -->
        </android.support.design.widget.CollapsingToolbarLayout>
    
    
        <!-- our tablayout to display tabs  -->
        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"
    
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
    
    
    </android.support.design.widget.AppBarLayout>
    
    
    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
    

  • Java file (move upper view down code)
    AppBarLayout ab = (AppBarLayout) findViewById(R.id.main_appbar);ab.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
    
            int ScrollStart = (ab.getHeight() - tabLayout.getHeight() - llTop.getHeight() - llTop.getHeight());
            int scrollStop = (ab.getHeight() - tabLayout.getHeight() - llTop.getHeight());
            if ((-verticalOffset) > ScrollStart && (-verticalOffset) < scrollStop) {
                llTop.setVisibility(View.VISIBLE);
                llTop.setTranslationY(((-verticalOffset) - ScrollStart) - llTop.getHeight());
                Log.e("point", "" + ((-verticalOffset) - ScrollStart));
    
            } else if ((-verticalOffset) >= scrollStop) {
                llTop.setVisibility(View.VISIBLE);
            } else {
                llTop.setVisibility(View.INVISIBLE);
            }
    
    
        }
    });
    


Get this bounty!!!

#StackBounty: #java #android #android-asynctask #google-api #location Get location on user state returns by ActivityRecognition

Bounty: 50

I need to get location(By fusedlocation API) of user after ActivityRecognition state returns(Which calls every 3 mins), like IN_VEHICLE,ON_FOOT,RUNNING etc.

On each event i need user location after regular interval For example:

if user is still then send location every 5 hours
if user is running then send location every 1 mins
if user is Driving then send location every 15 mins.

But i tried several ways but none of my logic works, which can send location after getting user state by ActivityRecognition .

Issue I am current having

  • ActivityRecognation Gets User State every 3 mins but it should not call location update until ‘LocationRequest.setInterval(Interval)’ LocationRequest.setInterval(FastestInterval); crossed.

Here is IntentService With FusedLocation

public class Activity_Recognized_Service extends IntentService implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks, LocationListener {
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public static final String TAG = "###RECOGNISED SRVCE###";
    Timer timer;
    GoogleApiClient LocationAPIclient;
    LocationRequest mLocationRequest;
    Location mCurrentLocation;
    boolean startLocationFirst=true;


    public Activity_Recognized_Service() {
        super("Activity_Recognized_Service");
    }

    public Activity_Recognized_Service(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.d(TAG, "On Handle Intent");
        if (ActivityRecognitionResult.hasResult(intent)) {
            Log.d(TAG, "ActivityRecognition Has Result");
            ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
            handleDetectedActivities(result.getProbableActivities());
            Navigation_Drawer nav = new Navigation_Drawer();
            nav.UserMovementResult(result);

        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG,"On Create Calling");
        if (LocationAPIclient == null) {
            Log.d(TAG, "Location API is NULL Value Of This ");
            LocationAPIclient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
        }

    }

    private void handleDetectedActivities(List<DetectedActivity> probableActivities) {

        for (DetectedActivity activity : probableActivities) {
            switch (activity.getType()) {
                case DetectedActivity.IN_VEHICLE:
                    Log.d(TAG, "In Vehicle " + activity.getConfidence());
                    if (activity.getConfidence() >= 75) {
                        //Send Notification To User
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
                        builder.setContentText("In Vehicle");
                        builder.setSmallIcon(R.drawable.elaxer_x);
                        builder.setContentTitle("Elaxer");
                        NotificationManagerCompat.from(this).notify(0, builder.build());
                        requestLocatonSetting(10*60*1000,8*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //5 hours= hours * 60 min*60 sec* 1000 milliseconds
                        //requestLocatonSetting(6*60*1000,6*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //TEST
                        LocationAPIclient.connect();
                        if (startLocationFirst){
                            Log.d(TAG,"Start Location Update For Car");
                        }
                    }
                    break;
                case DetectedActivity.ON_BICYCLE:
                    Log.d(TAG, "On Bicycle " + activity.getConfidence());
                    if (activity.getConfidence() >= 75) {
                        //Send Notification To User
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
                        builder.setContentText("On Bicycle");
                        builder.setSmallIcon(R.drawable.elaxer_x);
                        builder.setContentTitle("Elaxer");
                        NotificationManagerCompat.from(this).notify(0, builder.build());
                        requestLocatonSetting(7*60*1000,5*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //5 hours= hours * 60 min*60 sec* 1000 milliseconds
                        //requestLocatonSetting(6*60*1000,6*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //TEST
                        LocationAPIclient.connect();
                    }
                    break;
                case DetectedActivity.ON_FOOT:
                    Log.d(TAG, "On Foot " + activity.getConfidence());
                    if (activity.getConfidence() >= 75) {
                        //Send Notification To User
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
                        builder.setContentText("On Foot");
                        builder.setSmallIcon(R.drawable.elaxer_x);
                        builder.setContentTitle("Elaxer");
                        NotificationManagerCompat.from(this).notify(0, builder.build());
                    }
                    break;
                case DetectedActivity.RUNNING:
                    Log.d(TAG, "On Running " + activity.getConfidence());
                    if (activity.getConfidence() >= 75) {
                        //Send Notification To User
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
                        builder.setContentText("Running");
                        builder.setSmallIcon(R.drawable.elaxer_x);
                        builder.setContentTitle("Elaxer");
                        NotificationManagerCompat.from(this).notify(0, builder.build());
                        requestLocatonSetting(3*60*1000,2*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //5 hours= hours * 60 min*60 sec* 1000 milliseconds
                        //requestLocatonSetting(6*60*1000,6*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //TEST
                        LocationAPIclient.connect();
                    }
                    break;
                case DetectedActivity.STILL:
                    Log.d(TAG, "On Still " + activity.getConfidence());
                    if (activity.getConfidence() >= 75) {
                        //Send Notification To User
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
                        builder.setContentText("Still");
                        builder.setSmallIcon(R.drawable.elaxer_x);
                        builder.setContentTitle("Elaxer");
                        NotificationManagerCompat.from(this).notify(0, builder.build());

                            requestLocatonSetting(5*60*60*1000,3*60*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //5 hours= hours * 60 min*60 sec* 1000 milliseconds
                          //  requestLocatonSetting(3*60*1000,2*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //TEST
                            LocationAPIclient.connect();


                    }
                    break;
                case DetectedActivity.TILTING:
                    Log.d(TAG, "On Tilting " + activity.getConfidence());
                    if (activity.getConfidence() >= 75) {
                        //Send Notification To User
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
                        builder.setContentText("Tilting");
                        builder.setSmallIcon(R.drawable.elaxer_x);
                        builder.setContentTitle("Elaxer");
                        NotificationManagerCompat.from(this).notify(0, builder.build());

                        requestLocatonSetting(3*60*1000,2*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //5 hours= hours * 60 min*60 sec* 1000 milliseconds
                        //requestLocatonSetting(6*60*1000,6*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //TEST
                        LocationAPIclient.connect();
                    }
                    break;
                case DetectedActivity.WALKING:
                    Log.d(TAG, "On Walking " + activity.getConfidence());
                    if (activity.getConfidence() >= 75) {
                        //Send Notification To User
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
                        builder.setContentText("Let's Walk");
                        builder.setSmallIcon(R.drawable.elaxer_x);
                        builder.setContentTitle("Elaxer");
                        NotificationManagerCompat.from(this).notify(0, builder.build());
                        requestLocatonSetting(3*60*1000,2*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //5 hours= hours * 60 min*60 sec* 1000 milliseconds
                        LocationAPIclient.connect();

                    }
                    break;
                case DetectedActivity.UNKNOWN:
                    Log.d(TAG, "UnKnown " + activity.getConfidence());
                    break;
            }
        }
    }

    public void setTimer(int Minutes) {
        Log.d(TAG, "==================================================");
        Log.d(TAG, "Set Timeer Starts It will Run Every " + Minutes);
        int MilliSeconds = 60000 * Minutes;
        final Handler handler = new Handler();
        timer = new Timer();
        TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                        try {
                            //CODE THAT YOU WANT TO EXECUTE AT GIVEN INTERVAL


                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                        }
                    }
                });
            }
        };
        timer.schedule(doAsynchronousTask, 0, MilliSeconds);
        Log.d(TAG, "==================================================");
    }


    @Override
    public void onConnected(@Nullable Bundle bundle) {
        Log.d(TAG, "On Connected Running");
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
         mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(LocationAPIclient);
        if (mCurrentLocation!=null){
            Log.d(TAG,"Last Known Location Is not Null ");
            new Location_sendeToServer_AsyncTask(this).execute(String.valueOf(mCurrentLocation.getLatitude()),String.valueOf(mCurrentLocation.getLongitude()),String.valueOf(mCurrentLocation.getAccuracy()));
        }
        else {
            Log.d(TAG,"Last Known Location Is NULL Start Location Updates");
            LocationServices.FusedLocationApi.requestLocationUpdates(LocationAPIclient,mLocationRequest,this);
        }

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d(TAG,"On Location Changed Calling");
        mCurrentLocation=location;
        new Location_sendeToServer_AsyncTask(this).execute(String.valueOf(mCurrentLocation.getLatitude()),String.valueOf(mCurrentLocation.getLongitude()),String.valueOf(mCurrentLocation.getAccuracy()));
        Log.d(TAG,"Stopping Location Update");
       // LocationServices.FusedLocationApi.removeLocationUpdates(LocationAPIclient,this);
    }

    public void requestLocatonSetting(int Interval,int FastestInterval,int LocationAccuracy){
        mLocationRequest=new LocationRequest();
        mLocationRequest.setInterval(Interval);
        mLocationRequest.setFastestInterval(FastestInterval);
        mLocationRequest.setPriority(LocationAccuracy);

    }

}


Get this bounty!!!