本章节翻译自《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提示。
例子很简单,使用广播机制进行线程间的通信。