【问题标题】:button triggering function and intent at the same time. Android按钮触发功能和意图同时进行。安卓
【发布时间】:2018-09-02 09:08:44
【问题描述】:

所以我是 android 和 java 的新手,我知道我应该在有意图的活动之间移动。

Intent randomintent = new Intent(profile.this, loggedactivity.class);
randomintent .putString("name", namestring);
startActivity(randomintent);

问题是,我还有一个函数,我希望它在此意图将用户带到另一个活动之前执行。所以我的代码看起来像这样。

btnUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                uploadImage();
//this uploads the image, it works without the intent i added


    infosendstuff();
    //this should be executed after the image is uploaded and stores the image link to a database (also works)
   Intent randomintent = new Intent(profile.this, loggedactivity.class);
    randomintent .putString("name", namestring);
    startActivity(randomintent);        
    }
});

问题似乎是意图,在使用时,它忽略了它上面的其他两个功能,即上传图片并存储该图片的链接。 目标是上传图片,一旦完成,获取链接,通过意图(使用捆绑包)将链接发送到另一个活动,仅此而已。

【问题讨论】:

  • 请分享uploadImage()infosendstuff()的代码
  • 您的捆绑包似乎无处可去。您是否考虑过使用putExtra()
  • @jake 我试过了,但它也可以这样工作!
  • 但是当您在另一个Activity 中检索它时,您是否获得了价值?并请发布uploadImage() infosendstuff() 方法

标签: java android function android-studio android-intent


【解决方案1】:

最好使用AsynkTask

创建一个类,它应该从AsynkTask 扩展。在doInBackground,上传您的照片,处理回复并发送链接。并在onPostExecute 方法中,转到其他活动。

更新 1

class myClass extends AsyncTask<Void,Void,Void>{

        @Override
        protected Void doInBackground(Void... params) {
            String result = uploadPhotos();
            proccess result;
            send links;
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            Intent randomintent = new Intent(profile.this, loggedactivity.class);
            randomintent .putString("name", namestring);
            startActivity(randomintent);
        }
    }

现在你可以像这样使用它了:

new myClass().execute();

但在编码之前,我认为您需要更多地研究android中的网络连接过程。

【讨论】:

  • 您能举个例子说明我如何使用这种方法吗?谢谢!
【解决方案2】:

似乎uploadImage() 方法在网络上做了一些事情,由于网络请求和响应是在另一个线程中完成的,因此代码继续执行并且记录的活动将在uploadImage() 方法完成之前显示。

所以一种方法是强制主线程等待网络线程,在网络线程完成后,主线程继续工作,但会导致 UI 线程冻结。

另一种方法是您应该使用回调,当uploadImage() 方法完成时,某些方法将调用,并在该方法中开始您的新活动。类似于下面的代码:

uploadImage(new ResponeListener() { 
                 @override
                 public void onDataReady(String nameString) {
                    Intent randomintent = new Intent(profile.this,loggedactivity.class);
                    Bundle b = new Bundle();
                    b.putString("name", namestring);
                    startActivity(randomintent);
                 }
    }

【讨论】:

  • 这似乎合乎逻辑。谢谢!但是你知道我是否也适合 infosendstuff();这个ondataready里面的方法?那么图片上传完成后可以触发吗?
  • 是的,但是你应该考虑到如果 infosendstuff() 也在网络上做一些工作,那么活动将在 infosendstuff() 方法完成之前显示。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-27
  • 2011-01-18
  • 2012-05-21
  • 1970-01-01
  • 2022-12-12
  • 1970-01-01
  • 2018-01-19
相关资源
最近更新 更多