【问题标题】:Receiving a shared URL from another app into my Android app not working从另一个应用程序接收共享 URL 到我的 Android 应用程序不起作用
【发布时间】:2022-09-24 00:41:38
【问题描述】:

我是 Android 应用程序开发的新手。我正在尝试制作一个执行以下操作的应用程序:

  1. 我打开我的应用程序
  2. 我离开我的应用程序并让它在后台运行
  3. 我从另一个应用程序共享了一个指向我的应用程序的链接(我尝试了 YouTube)
  4. 我的应用程序在其 TextView 上显示链接。

    我正在关注本指南:https://developer.android.com/training/sharing/receive#java

    但是,当我分享应用程序的链接时,TextView 没有得到更新。事实上,链接甚至没有被意图首先接收。

    这是我的MainActivity.java,没有生成包含共享链接的TextReceived 日志:

        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);
                }
            }
        }
    

    这是我的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>
    

    这是我的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>
    

    这是调试面板日志:

    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
    

    我尝试在MainActivity.javaonResumeonPause 生命周期下引入与意图相关的函数和声明,但这也不起作用。我尝试删除handleSendText() 函数并在现场做所有事情,这并不奇怪。

    我真的很想要一个即使应用程序关闭也能工作的解决方案,因为我计划完全阻止显示活动,而是在后台做所有事情(并使用共享链接做其他事情)。请在这里帮助我,在此先感谢!

  • \“我真的很想要一个即使应用程序关闭也能工作的解决方案,因为我打算完全阻止显示活动\”——这不是ACTION_SEND 的选项。关于您当前的问题,onCreate() 仅在创建活动时调用,在您的情况下,它已经创建。您还需要覆盖onNewIntent() 并能够以这种方式处理ACTION_SEND
  • @CommonsWare 非常感谢您的建议。现在,即使应用程序关闭,它也能完美运行。

标签: java android android-layout android-intent


【解决方案1】:

根据@CommonsWare 的评论,我尝试了解更多信息,这就是有效的:

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
        }
    }

基本上把getIntent()方法放在onResume()里面,然后从onNewIntent()处理setIntent()

这个答案真的很有帮助:https://stackoverflow.com/a/8896750/20059147

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多