如何在android中使用服务显示图像

时间:2014-02-27 08:43:52

标签: android android-layout android-service android-imageview android-file

我想要展示图片。我必须在服务中执行操作并在UI中显示结果。我不想根据要求使用异步任务。我不知道如何继续和显示图像。请帮帮我。

我的代码如下:

 public class Service_Photo extends Service {

        public Service_Photo() {

        }

        @Override

        public IBinder onBind(Intent intent) {

            throw new UnsupportedOperationException("Not yet implemented");

        }

        @Override

        public void onCreate() {
            super.onCreate();    
            Toast.makeText(this, "The new Service was Created", Toast.LENGTH_LONG).show();

        }

        @Override

        public void onStart(Intent intent, int startId) {

            // For time consuming an long tasks you can launch a new thread here...

            Toast.makeText(this, " Service Started", Toast.LENGTH_LONG).show();

            updateImages();

        }
        private void updateImages()
        {
            String baseDir =  Environment.getExternalStorageDirectory().getAbsolutePath();
            String fileName = "am/a.jpg";
            File f = new File(baseDir + File.separator + fileName);
            if(f.exists()){

                Bitmap myBitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
            //     img = (ImageView)findViewById(R.id.image);
            // img.setImageBitmap(myBitmap);
                Toast.makeText(getApplicationContext(), "Hello"+myBitmap.toString(), Toast.LENGTH_SHORT)
                .show();

            }
        }



        @Override

        public void onDestroy() {

            Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();

        }

       public class ImageDisplay extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
            //how to display the operation performed in service and display in image from service?
    }
    }

1 个答案:

答案 0 :(得分:0)

您的最佳解决方案是使用广播接收器。所以在你的活动中

 BroadcastReceiver mReceiver = new BroadcastReceiver(onReceive(Context context, Intent intent)
    {
    if(intent.getAction().equals("your_load_photo_action"))
    {
           ImageDisplay.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                view.setImageBitmap("YourImage");
            }
            });
    }
    });

    @Override
    public void onResume()
    {
     LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
          new IntentFilter("your_load_photo_action"));
    }

    @Override
    public void onPause()
    {
     LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
    }

并在onCreate()初始化视图

在您的服务中,updateImages() 只需使用“your_load_photo_action”

操作发送广播意图