在Android中从Intent检索调用活动



我正试图传递我的活动指针,但我不知道如何检索它。

我有一个调用活动(MyActivity),其中包含以下代码片段:

Intent myServiceIntent = new Intent(this, myService.class);
startService(myServiceIntent);

在我的服务类中,我想检索调用活动。类似这样的东西:

private Activity CurrentActivity = null;    
public int onStartCommand(Intent intent, int flags, int startId) 
    {
        CurrentActivity = (CurrentActivity) intent.getClass();
        return super.onStartCommand(intent, flags, startId);
    }

这不起作用,但我也不知道是什么起作用。我也找不到将活动作为参数的putExtra。那么我该怎么做呢?

在第一个活动中,取一个静态活动变量,如

public static Activity activity;

在onCreate中执行此操作。

activity = this;

然后在第二个活动中这样做,

Activity activity = (your activity name).activity;

据我所知,这是最好的解决方案。只需为这样的变量传递一个代码/值。

Intent intent = new Intent();
intent.putExtra("someValue", "data");

在第二个活动中,检查值,如果该值是您的必需值,则获取您的必需活动实例。我希望这能解决你的问题,如果能的话,请告诉我。

您还可以获得调用活动的信息

val uriString= intent.toUri(Intent.URI_INTENT_SCHEME)

只需在类似的附加文件中发送活动名称

startActivity(new Intent(this, otherActivity.class).putExtra("from" , "previousActivity"));

并在当前活动中获得额外的

string act = getIntent().getStringExtra("from");
Class callerClass = Class.forName(caller);

希望它能解决你的问题。

最新更新