从一个单独的线程启动活动?线程

2023-09-06 14:31:15 作者:很久没笑了

我有一个Android应用程序,需要在主线程中的照片,并创建一个新的线程,以这个图像发送到服务器并接收响应。现在,我要保存服务器在我的手机的联系人列表发送的信息,我试图用下面的code,开始对这个新线程活动:

I have an android application that takes a photograph in the main thread and creates a new thread in order to send this image to the server and receives the response. Now, I want to save the information sent by the server in the contact list of my phone, for that I am trying to start an activity on this new thread using the following code:

private void addContact() {

    Intent intent = new Intent(Intent.ACTION_INSERT);
    intent.setType(ContactsContract.Contacts.CONTENT_TYPE);

    intent.putExtra(ContactsContract.Intents.Insert.NAME, DisplayName);
    intent.putExtra(ContactsContract.Intents.Insert.PHONE, WorkNumber);
    intent.putExtra(ContactsContract.Intents.Insert.EMAIL, emailID);

    this.startActivity(intent);

}

但他抛出了我的错误:的onCreate()之前,系统服务不可用活动

我觉得这个消息的是,因为在这个新的线程它没有任何onCreate()方法,那就是它抛出这个错误的原因。

What I think of this message is that since in this new thread it doesn't have any onCreate() method, that is the reason it throws this error.

谁能告诉我我应该怎么开始这项活动。

Can someone tell me how should I start this activity.

推荐答案

,尝试使用的AsyncTask

请在网​​络调用doInBackground()并返回一个捆绑或服务器响应的String [] 阵列 onPostExecute()

Make the network call in doInBackground() and return the server response in a Bundle or a String[] array to onPostExecute().

onPostExecute(),服务器数据添加到意图,然后调用 startActivity()

In onPostExecute(), add the server data to the intent and then call startActivity().

试试这个。它将工作。因为你调用 startActivity()在另一个线程你得到一个错误。你需要调用它的主(UI)线程。

Try this. It will work. You are getting an error because you are calling startActivity() on another thread. You need to call it on the main (UI) thread.

 
精彩推荐
图片推荐