【Android 开发教程】在Activity和Service之间建立链接

本文通过实例演示了如何在Android应用中实现Service与Activity之间的通信。具体介绍了如何使用IntentService下载文件并在完成后通知Activity。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本章节翻译自《Beginning-Android-4-Application-Development》,如有翻译不当的地方,敬请指出。

原书购买地址http://www.amazon.com/Beginning-Android-4-Application-Development/dp/1118199545/


通常,service总是在它自己的线程里面执行任务,和调用它的activity线程是相互独立的。如果service只是在后台执行一些循环任务,并且不关心service的状态,是不会产生问题的。举个例子,有一个service在后台打印当前设备的地理位置信息。这种情况下,service不需要和任何activity进行交互。因为,service的主要任务就是打印日志。

然而,想像一下,你想要监视一个特定的地理位置,当设备靠近这个地理位置的时候,service打印地址信息,这时,就需要和activity就行交互。下面的例子展示如果实现service和activity之间的交互。

1. 使用Services工程,修改MyIntentService.java文件。

public class MyIntentService extends IntentService {

    public MyIntentService() {
        super("MyIntentServiceName");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        try {
            int result =
                DownloadFile(new URL("http://www.amazon.com/somefile.pdf"));
            Log.d("IntentService", "Downloaded " + result + " bytes");
            
            //---send a broadcast to inform the activity
            // that the file has been downloaded---
            Intent broadcastIntent = new Intent();
            broadcastIntent.setAction("FILE_DOWNLOADED_ACTION");
            getBaseContext().sendBroadcast(broadcastIntent);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    private int DownloadFile(URL url) {
        try {
            //---simulate taking some time to download a file---
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 100;
    }
}

2. 修改ServicesActivity.java文件。

public class ServicesActivity extends Activity {
    IntentFilter intentFilter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
    @Override
    public void onResume() {
    	super.onResume();

        //---intent to filter for file downloaded intent---
        intentFilter = new IntentFilter();
        intentFilter.addAction("FILE_DOWNLOADED_ACTION");

        //---register the receiver---
        registerReceiver(intentReceiver, intentFilter);
    }
    
    @Override
    public void onPause() {
    	super.onPause();
    	
    	//---unregister the receiver---
    	unregisterReceiver(intentReceiver);
    }
    
    public void startService(View view) {
        startService(new Intent(getBaseContext(), MyIntentService.class));
    }
    
    public void stopService(View view) {
        stopService(new Intent(getBaseContext(), MyService.class));
    }

    private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(getBaseContext(), "File downloaded!",
                    Toast.LENGTH_LONG).show();
        }
    };

}

3. 在模拟器上面调试。

4. 点击start service按钮,大概5秒后会弹出toast提示。


例子很简单,使用广播机制进行线程间的通信。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值