Home > Enterprise >  Receiving a shared URL from another app into my Android app not working
Receiving a shared URL from another app into my Android app not working

Time:09-27

I am new to Android app development. I am trying to make an app which does the following:

  1. I open my app
  2. I leave my app and keep it running in the background
  3. I share a link to my app from another app (I tried YouTube)
  4. My app displays the link on its TextView.

And I am following this guide: https://developer.android.com/training/sharing/receive#java

However, when I share the link to the app, the TextView is not getting updated. In fact, the link is not even being received by the intent in the first place.

Here is my MainActivity.java, no TextReceived log containing the shared link was being produced:

    import androidx.appcompat.app.AppCompatActivity;
    
    import android.util.Log;
    
    import android.content.Intent;
    import android.os.Bundle;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Intent intent = getIntent();
            String action = intent.getAction();
            String type = intent.getType();
            if (Intent.ACTION_SEND.equals(action) && type != null) {
                if ("text/plain".equals(type)) {
                    handleSendText(intent); // Handle text being sent
                } else {
                    Toast toast = Toast.makeText(getApplicationContext(), "Please share an url", Toast.LENGTH_SHORT);
                    toast.show();
                }
            }
        }
    
        void handleSendText(Intent intent){
            String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
            Log.d("Textreceived", sharedText);
            if (sharedText != null) {
                TextView helloTextView = (TextView) findViewById(R.id.TextView1);
                helloTextView.setText(sharedText);
            }
        }
    }

Here is my activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/nothing"
        android:id="@ id/TextView1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

And here is my AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.SimpleVideoDownloader"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="text/plain" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>

</manifest>

And here is the debug panel logs:

Connected to the target VM, address: 'localhost:52211', transport: 'socket'
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/videodownloade: Late-enabling -Xcheck:jni
D/ProcessState: Binder ioctl to enable oneway spam detection failed: Invalid argument
D/CompatibilityChangeReporter: Compat change id reported: 171979766; UID 10291; state: ENABLED
D/AppScoutStateMachine: 32132-ScoutStateMachinecreated
W/ActivityThread: Application com.example.simplevideodownloader is waiting for the debugger on port 8100...
I/System.out: Sending WAIT chunk
I/System.out: Debugger has connected
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1391)
W/ziparchive: Unable to open '/data/app/~~_1ZXNj-gpkC0bM-o-_LQYg==/com.example.simplevideodownloader-4o9AfRTKkroRKixsJBmZrA==/base.dm': No such file or directory
W/ziparchive: Unable to open '/data/app/~~_1ZXNj-gpkC0bM-o-_LQYg==/com.example.simplevideodownloader-4o9AfRTKkroRKixsJBmZrA==/base.dm': No such file or directory
I/Perf: Connecting to perf service.
V/GraphicsEnvironment: ANGLE Developer option for 'com.example.simplevideodownloader' set to: 'default'
V/GraphicsEnvironment: Updatable production driver is not supported on the device.
I/ForceDarkHelperStubImpl: initialize for com.example.simplevideodownloader , ForceDarkOrigin
D/OpenGLRenderer: JNI_OnLoad success
I/MiuiForceDarkConfig: setConfig density:2.750000, mainRule:0, secondaryRule:0, tertiaryRule:0
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/Looper: PerfMonitor longMsg : seq=3 plan=13:40:49.370 late=2ms wall=2457ms running=196ms runnable=29ms swapin=10ms binder=32ms h=android.app.ActivityThread$H w=110 procState=-1
D/ViewScrollStubImpl: the value of ScrollFrictionRes is: 0.019499999
D/IS_CTS_MODE: false
D/MULTI_WINDOW_SWITCH_ENABLED: false
D/IS_CTS_MODE: false
D/MULTI_WINDOW_SWITCH_ENABLED: false
D/IS_CTS_MODE: false
D/MULTI_WINDOW_SWITCH_ENABLED: false
D/DecorView[]: getWindowModeFromSystem  windowmode is 1
W/Looper: PerfMonitor looperActivity : package=com.example.simplevideodownloader/.MainActivity time=276ms latency=2464ms running=213ms  procState=-1  historyMsgCount=3 (msgIndex=1 wall=276ms seq=4 running=213ms runnable=32ms swapin=21ms binder=20ms late=2464ms h=android.app.ActivityThread$H w=159) (msgIndex=2 wall=276ms seq=4 running=213ms runnable=32ms swapin=21ms binder=20ms late=2464ms h=android.app.ActivityThread$H w=159) (msgIndex=3 wall=2457ms seq=3 running=196ms runnable=29ms swapin=10ms binder=32ms late=2ms h=android.app.ActivityThread$H w=110)
W/Looper: PerfMonitor looperActivity : package=com.example.simplevideodownloader/.MainActivity time=0ms latency=2740ms running=0ms  procState=-1  historyMsgCount=4 (msgIndex=1 wall=276ms seq=4 running=213ms runnable=32ms swapin=21ms binder=20ms late=2464ms h=android.app.ActivityThread$H w=159) (msgIndex=2 wall=276ms seq=4 running=213ms runnable=32ms swapin=21ms binder=20ms late=2464ms h=android.app.ActivityThread$H w=159) (msgIndex=3 wall=2457ms seq=3 running=196ms runnable=29ms swapin=10ms binder=32ms late=2ms h=android.app.ActivityThread$H w=110) (msgIndex=4 wall=276ms seq=4 running=213ms runnable=32ms swapin=21ms binder=20ms late=2464ms h=android.app.ActivityThread$H w=159)
I/AdrenoGLES-0: QUALCOMM build                   : c5f0e23, I9972db7aac
    Build Date                       : 04/28/21
    OpenGL ES Shader Compiler Version: EV031.32.02.10
    Local Branch                     : mybrancheba83f1e-3815-f156-b760-08f1eafda2d8
    Remote Branch                    : quic/gfx-adreno.lnx.1.0.r99-rel
    Remote Branch                    : NONE
    Reconstruct Branch               : NOTHING
I/AdrenoGLES-0: Build Config                     : S P 10.0.7 AArch64
I/AdrenoGLES-0: Driver Path                      : /vendor/lib64/egl/libGLESv2_adreno.so
I/AdrenoGLES-0: PFP: 0x016ee190, ME: 0x00000000
D/hw-ProcessState: Binder ioctl to enable oneway spam detection failed: Invalid argument
E/videodownloade: open libmigui.so failed! dlopen - dlopen failed: library "libmigui.so" not found
D/DecorView[]: onWindowFocusChanged hasWindowFocus true
D/DecorView[]: onWindowFocusChanged hasWindowFocus false
D/AppScoutStateMachine: 32132-ScoutStateMachinecreated
I/OpenGLRenderer: Davey! duration=20858ms; Flags=1, FrameTimelineVsyncId=4974711, IntendedVsync=86204996072645, Vsync=86204996072645, InputEventId=0, HandleInputStart=86204997541436, AnimationStart=86204997554509, PerformTraversalsStart=86204997559040, DrawStart=86205055184092, FrameDeadline=86205029405977, FrameInterval=86204996896748, FrameStartTime=16666666, SyncQueued=86205057721227, SyncStart=86205057776748, IssueDrawCommandsStart=86205059246540, SwapBuffers=86205102629769, FrameCompleted=86225854180230, DequeueBufferDuration=8825157, QueueBufferDuration=1841250, GpuCompleted=86225854180230, SwapBuffersCompleted=86205106817061, DisplayPresentTime=227721, 
D/DecorView[]: onWindowFocusChanged hasWindowFocus true

I tried bringing the intent-related functions and declarations in MainActivity.java under onResume and onPause lifecycles, but that didn't work either. I tried removing the handleSendText() function and doing everything on spot, which unsurprisingly didn't work out.

I would really like a solution which would work even if the app is closed, as I plan to prevent displaying an activity at all, and do everything in the background instead (and do something else with the shared link). Please help me out here, thanks in advance!

CodePudding user response:

As per @CommonsWare 's comment, I tried finding out more, and this is what works:

public class MainActivity extends AppCompatActivity {

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

    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = getIntent();
        String action = intent.getAction();
        String type = intent.getType();
        if (Intent.ACTION_SEND.equals(action) && type != null) {
            if ("text/plain".equals(type)) {
                handleSendText(intent); // Handle text being sent
            } else {
                Toast toast = Toast.makeText(getApplicationContext(), "Please share an url", Toast.LENGTH_SHORT);
                toast.show();
            }
        }
    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    void handleSendText(Intent intent){
        String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
        Log.d("Textreceived", sharedText);
        if (sharedText != null) {
            //my work here
        }
    }

Basically put the getIntent() method inside onResume() and handle setIntent() from onNewIntent().

This answer was really helpful: https://stackoverflow.com/a/8896750/20059147

  • Related