【问题标题】:calling three methods simultaneously in database [closed]在数据库中同时调用三个方法[关闭]
【发布时间】:2013-12-16 05:50:41
【问题描述】:

我必须在广播接收器中同时调用三个不同的方法(比如方法 a、b、c)。 .我的问题是如何调用这些方法来获取所有数据。

public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        getA();
        getB();
        getC();
    }
public void getA(){
//code here
}
public void getB(){
//code here
}
public void getc(){
//code here
}

我必须在数据库(公共 ip)中发送这些方法的值。

请分享一些相关代码来解决这个问题。 谢谢。

【问题讨论】:

  • 到目前为止你尝试过什么?
  • 我已经创建了方法。例如 A,B.并在 onReceive 方法中调用它。
  • onReceive(){getA();getB();}
  • 但是这里只调用了一个方法,如果有两个或更多怎么办

标签: android broadcastreceiver


【解决方案1】:

在 Android 中进行线程处理的最简单方法是使用 AsyncTask。

我不确定您是否愿意为这些方法中的每一个传递一个参数,或者您是否希望从它们那里得到任何回报;但让我们假设您没有通过或期待任何事情。

public void onReceive(Context context, Intent intent) {
    // start the first method
    new AsyncTask<Integer, Integer, Integer>() {
        @Override
        protected Integer doInBackground(Integer... params) {
            getA();
        }
    }.execute();
    // start the second method
    new AsyncTask<Integer, Integer, Integer>() {
        @Override
        protected Integer doInBackground(Integer... params) {
            getB();
        }
    }.execute();
    // start the third method
    new AsyncTask<Integer, Integer, Integer>() {
        @Override
        protected Integer doInBackground(Integer... params) {
            getC();
        }
    }.execute();
}

&lt;Integer, Integer, Integer&gt; 参数代表您要传递给任务的参数类型、进度更新类型和返回结果类型。

如果您想为每个方法传递一些参数,请将第一个 Integer 更改为您要传递的参数类型,然后将这些参数添加到 execute() 方法中。


如果您想启动一个活动并从接收器向其发送一些数据,您应该使用 Intent 来完成。

public void getA(Context context, Object dataToPass) {
    // replace DestinationActivity with the Activity that you want to start
    Intent i = new Intent(context, DestinationActivity.class);
    // add the data that you want to pass
    i.putExtra("some-constant", dataToPass);
    // start the actual activity
    context.startActivity(i);
}

在这种情况下,您必须在 onReceive() 方法中更改对 getA() 的调用,以添加上下文和要传递的数据。

参考:http://developer.android.com/reference/android/os/AsyncTask.html

【讨论】:

  • 你的代码对我真的很有帮助。最重要的是我正在通过它检索一些数据并希望在活动类的列表视图中显示它。所以,我如何在活动类中调用这些数据以在列表视图上设置
  • 您检索的数据是什么?根据它是什么,您可能能够在 Activity 上实现一个方法,该方法将数据作为参数并更新列表视图
  • 等等,你的意思是你不能获取到正在运行的activity实例的引用吗?
  • 其通话记录数据、网络记录数据和电话信息。
  • 是的,我无法在活动中调用这些数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多