從活動到服務的單向通信,服務無限期運行,直到活動命令它停止。只有一種方式,即活動來服務交流的最佳方式?
0
A
回答
0
您可以使用廣播接收器的服務與活動之間的通信
你的服務應該是這樣的: -
public class MyService extends Service {
private static final String TAG = "com.example.ServiceExample";
@Override
public void onCreate() {
Log.i(TAG, "Service onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//SendBroadCast to Activity
Intent intent = new Intent("my-event");
intent.putExtra("message", "data");
sendBroadcast(intent);
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
Log.i(TAG, "Service onBind");
return null;
}
@Override
public void onDestroy() {
Log.i(TAG, "Service onDestroy");
}
}
你的活動應該是這樣的: -
public class BindingActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onStop() {
super.onStop();
}
/** Called when a button is clicked (the button in the layout file attaches to
* this method with the android:onClick attribute) */
public void onButtonClick(View v) {
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
@Override
public void onResume() {
super.onResume();
// Register mMessageReceiver to receive messages.
registerReceiver(mMessageReceiver,
new IntentFilter("my-event"));
}
@Override
protected void onPause() {
// Unregister since the activity is not visible
unregisterReceiver(mMessageReceiver);
super.onPause();
} }
}
相關問題
- 1. 社交活動流的最佳模式?
- 2. 安卓服務通知活動完成最佳方式?
- 3. 爲什麼交換隻有一種方式,而不是另一種方式?
- 4. 的最佳方式從服務器
- 5. 等待WCF服務的最佳方式?
- 6. 最佳方式交互
- 7. 最佳方式初始化活動ViewPager
- 8. 構建這種遠程服務的最佳方式是什麼?
- 9. 打開TCP流到服務器的最佳方式是什麼?
- 10. 最佳流式播放方式
- 11. 服務與用戶交互的最佳方式
- 12. 處理來自服務器的信息的最佳方式
- 13. 有沒有一種可靠的方式來啓動Android的啓動活動?
- 14. IBM BPM 8,5.6一種遍歷流程中活動的方式
- 15. 最佳方式來優化服務器上的30+ gb圖像
- 16. 最佳方式
- 17. 最佳方式
- 18. 最佳方式
- 19. 最佳方式
- 20. 最佳方式
- 21. 最佳方式
- 22. 最佳方式
- 23. 最佳方式
- 24. 最佳方式
- 25. 最佳方式
- 26. 最佳方式
- 27. 最佳方式
- 28. 最佳方式
- 29. 最佳方式
- 30. 最佳方式
看'上下文#startService()' – pskink
你能解釋一下嗎? –
閱讀'startService()'javadocs後不清楚什麼? – pskink