【问题标题】:How to start Activity from another project如何从另一个项目启动 Activity
【发布时间】:2016-12-04 03:54:28
【问题描述】:

我正在为 android 和 windows-phone 开发天气应用程序。所以我在“Parsing Class”的“Weather.Api(Portable)”的另一个项目中编写了通用代码。 “Weather.Droid”用于Android。

ParsingClass的代码如下:

    public static string tempGlobal;
    public static string cityTextGlobal;
    private static string GovnoTemperature;

    public async  Task<string> dataByCity(string city)
    {
        var url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&APPID="+AppID;

        //ТОРМОЗИТ ЗДЕСЬ / BRAKES HERE
        await FetchAsync(url);
        return city;
    }

    public async Task<double> Data_down(double lat, double lon)
    {

        var url = String.Format(
          "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&units=metric&APPID=" + AppID);

        //ТОРМОЗИТ ЗДЕСЬ / BRAKES HERE
        await FetchAsync(url);

        return lat;
    }

    public async Task<string> FetchAsync(string url)
    {
        string jsonString;

        using (var httpClient = new System.Net.Http.HttpClient())
        {
            var stream = await httpClient.GetStreamAsync(url);
            StreamReader reader = new StreamReader(stream);
            jsonString = reader.ReadToEnd();
        }

        var json = jsonString;

        JsonValue firstitem = json;
        var mydata = JObject.Parse(json);

        cityTextGlobal = (mydata["name"]).ToString();

        string GovnoData = (mydata["main"]).ToString();

        //spliting string
        string[] values = GovnoData.Split(',');
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = values[i].Trim();
            if (i == 0)
            {
                //tempGlobal = values[i];
                GovnoTemperature = values[i];
            }
        }
        tempGlobal = null;
        foreach (char c in GovnoTemperature)
        {
            if (c == '.')
            {
                break;
            }
            if (c == '-' || char.IsDigit(c) == true || c == '.')
            {
                tempGlobal += c.ToString();
            }
        }

        return jsonString;
    }
}

public class Coord
{
    public double lon { get; set; }
    public double lat { get; set; }
}

public class Weather
{
    public int id { get; set; }
    public string main { get; set; }
    public string description { get; set; }
    public string icon { get; set; }
}

public class Main
{
    public double temp { get; set; }
    public int pressure { get; set; }
    public int humidity { get; set; }
    public int temp_min { get; set; }
    public int temp_max { get; set; }
}

public class Wind
{
    public double speed { get; set; }
    public double deg { get; set; }
}

public class Clouds
{
    public int all { get; set; }
}

public class Sys
{
    public int type { get; set; }
    public int id { get; set; }
    public double message { get; set; }
    public string country { get; set; }
    public int sunrise { get; set; }
    public int sunset { get; set; }
}

public class RootObject
{
    public Coord coord { get; set; }
    public List<Weather> weather { get; set; }
    public string @base { get; set; }
    public Main main { get; set; }
    public int visibility { get; set; }
    public Wind wind { get; set; }
    public Clouds clouds { get; set; }
    public int dt { get; set; }
    public Sys sys { get; set; }
    public int id { get; set; }
    public string name { get; set; }
    public int cod { get; set; }
}

}

我需要从方法启动“Weather.Droid”的MainActivity:

公共异步任务 FetchAsync(字符串 url)

在它返回之前:

jsonString

我该怎么做?

【问题讨论】:

    标签: c# android json xamarin windows-phone


    【解决方案1】:

    看来您所追求的是依赖注入。在可移植项目中声明一个接口,然后在Droid/iOS/中实现?您支持的项目。

    我在 XLabs 社区项目中创建了 IOC 的抽象。 Matt Whetton 写了一些关于如何使用它的非常好的说明:http://www.codenutz.com/getting-started-xamarin-forms-labs-xaml-mvvm-ioc/

    以下方法并不理想,但有点不清楚为什么需要调用活动开始至少这会给你一些想法。

    在便携方面:

    public class Class1
    {
        public static async Task<string> Fetch(string url, Action onComplete = null)
        {
            await Task.Delay(10);
    
    
            onComplete?.Invoke();
            return url;
        }
    }
    

    在 Android 端(如果您的意图是在主屏幕出现之前执行此提取,这将是您的启动屏幕或应用程序):

    [Activity(Label = "App5", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
    
            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);
    
            Class1.Fetch("test", () =>
            {
                var intent = new Intent(this, typeof(OtherActivity));
                this.RunOnUiThread(() => StartActivity(intent));
            }).ContinueWith(t =>
            {
                if (t.IsCompleted) Log.Debug("Fetch", t.Result);
            });
        }
    }
    

    【讨论】:

    • 我只想从 ParsingClass 调用放置在 Weater.Droid 项目中的任何方法。这是我的问题。
    • 你是从 Android 项目中调用这个方法吗?如果是这样,您可以将 Action 添加到方法参数并在方法返回之前调用它。如果没有,那么国际奥委会是您的最佳选择。
    • 我写了公共方法,它在 android 项目中启动所需的活动。但问题是从 Weather.Api 项目中调用此方法。我试图做一个参考。但那是不可能的。此错误的文本是:无法添加参考 Weather.Droid。将此项目添加为引用会导致循环依赖
    【解决方案2】:

    我需要从方法启动“Weather.Droid”的MainActivity:

    公共异步任务 FetchAsync(字符串 url)

    您不能直接从 Droid 项目启动 MainActivity。但正如@SKall 所说,您可以在您的FetchAsync 方法中使用Action&lt;Intent&gt;

    //add Action<Intent> as and Intent as parameters
    public async Task<string> FetchAsync(string url,Action<Intent> navigationFunc,Intent intent)
    {
        string jsonString;
        ...
        navigationFunc(intent);//Invoke the action
        return jsonString;
    }
    

    然后在你的 Droid 项目中使用它:

    ParsingClass parsing = new ParsingClass();
    Intent intent = new Intent(this, typeof(MainActivity));
    await parsing.FetchAsync("url", StartActivity, intent);
    

    【讨论】:

    • Intent 位于 Android 命名空间中,因此您无法使用它。只需创建一个普通的 Action。
    猜你喜欢
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 1970-01-01
    相关资源
    最近更新 更多