簡體   English   中英

從服務傳遞意圖到FragmentActivity

[英]Passing Intent from Service to FragmentActivity

如何將額外的意圖從服務類傳遞給FragmentActivity類?

服務將意圖傳遞給FragmentActivity

  Intent intent = new Intent(getBaseContext(), Home.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent.putExtra("AlarmActivated", 1);

        startActivity(intent);

從服務傳遞的FragmentActivity接受意圖

Bundle extras = getIntent().getExtras();
        if (extras != null) {
            extras = getIntent().getExtras();
            stopMovementAlarm = extras.getInt("AlarmActivated");
            Toast.makeText(getApplicationContext(), stopMovementAlarm,
                    Toast.LENGTH_LONG).show();
            cd.setText("");
            showMyDialog();
            volumeMax();
            alternatingScreen();

        }

出於意圖,您尚未指定要啟動哪個活動,這就是您收到錯誤的原因。 您需要指定如下活動

Intent intent = new Intent(context, Activity.class);

我認為最好的方法是使用BroadcastReceiver傳遞意圖。 檢查此示例http://android-coding.blogspot.in/2011/11/pass-data-from-service-to-activity.html

eidt嘗試使用getApplicationContext()代替getBaseContext() 如果這樣不起作用,請嘗試如下操作:

//in your activity 

    private MyReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
          Bundle bundle = intent.getExtras();
          if (bundle != null) {
                int datapassed = bundle.getInt("DATAPASSED");

                Toast.makeText(getApplicationContext(), "Broadcast received",
                        Toast.LENGTH_LONG).show();
                cd.setText("");
                showMyDialog();
                volumeMax();
                alternatingScreen();
            }
          }
        }
    };

    @Override
    public void onResume(Bundle savedInstanceState) {
        IntentFilter intentFilter = new IntentFilter(SOME_ACTION);
        MyReceiver mReceiver = new MyReceiver();
        registerReceiver(mReceiver, intentFilter);
    }

//in your service somewhere
        Intent intent = new Intent(getApplicationContext(), Home.class);
        intent.putExtra("DATAPASSED", 1);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        sendBroadcast(intent);

我希望能解決它:)

我發現我的問題,活動之間傳遞值變得更為復雜一點點,當launchmode SingleTop被扔進代碼。

我需要將此方法放在我的onResume中。

@Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        // set the string passed from the service to the original intent
        setIntent(intent);

    }

當活動在活動堆棧的頂部重新啟動時,onNewIntent()在現有實例上調用並重新啟動活動,以便我的Intent可以刷新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM