簡體   English   中英

如何將位圖從服務發送到Java,Android中的main?

[英]How can I send bitmap from service to a main in java, android?

我正在應用程序中提供服務以下載圖像,這對我來說還不清楚如何將結果(位圖)從服務發送到主要活動。 我可以那樣做嗎? 還是在使用中,只能將下載的圖像保存在某處並僅發送無用的消息?

嘗試從活動綁定到服務,然后將活動實例傳遞給服務。 在這種情況下,您可以將位圖從服務傳遞到活動。 但是,您需要非常小心,不要引入內存泄漏

像這樣:

class TestActivity extends Activity {
    private BitmapService mBitmapService;
    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName,
                                       IBinder iBinder) {
            BitmapService.BitmapServiceBinder mBinder = (BitmapService.BitmapServiceBinder) iBinder;
            mBitmapService = mBinder.getBitmapService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        bindService(new Intent(this, XMLDownloaderService.class), mServiceConnection, BIND_AUTO_CREATE);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(this.mServiceConnection);
    }
}

您的服務端:

public class BitmapService extends BitmapService {

    public class BitmapServiceBinder extends Binder {
        public BitmapService getBitmapService() {
             return BitmapService.this;
        }
    }

     public BitmapService() {
        super("BitmapService");
     }

     @Override
     public IBinder onBind(Intent intent) {
         return mBinder;
     }

     @Override
     public void onCreate() {
          super.onCreate();
           if (mBinder == null) {
               mBinder = new BitmapServiceBinder();
           }
     }
}

Bitmap實現了Parcelable ,因此您可以始終按意圖傳遞它:

Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", bitmap);

並在另一端檢索它:

Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");

如果位圖以文件或資源的形式存在,則最好傳遞位圖的URI或ResourceID,而不是位圖本身。 傳遞整個位圖需要大量內存。 傳遞URL所需的內存很少,並且允許每個活動根據需要加載和縮放位圖。

答案來自: 如何將位圖對象從一個活動傳遞到另一個活動

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM